前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >92-R可视化24-与ggplot图例较劲

92-R可视化24-与ggplot图例较劲

作者头像
北野茶缸子
发布2022-02-08 15:25:09
2.9K0
发布2022-02-08 15:25:09
举报
  • Date : [[2022-01-06_Thu]]
  • Tags : #R/index/02 #R/R可视化 #R/R数据科学 #其他/答粉丝问题

前言

感觉ggplot 绘图中的图例/legend,完全可以作为一个单独的内容讲很久,特此来总结一下。

1-移除全部/部分图例

使用legend.position = "none" 可以方便我们移除图例,但有时候可能并不需要这么无情,比如移除指定某个类型的图例,通常几何对象可以设置多种分类(color, fill, shape..),我们可以使用guide 函数:

代码语言:javascript
复制
ggplot(chic,
       aes(x = date, y = temp,
           color = season, shape = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  guides(color = "none")

另外scale_xx_discrete 函数亦可指定guide 参数,比如 scale_shape_discrete(guide = "none")

2-移除图例标题

theme(legend.title = element_blank()),我们也可以在labs 中,按照aes 定义的对应内容,直接创建空白的名称:

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)",
       color = "")

我们亦可以使用scale_xx_discrete 定义,如 scale_color_discrete(name = "Seasons\nindicated\nby colors:")

3-改变图例标题和子标签

改变图例标题的方法有很多,关于子标签,可以使用scale_xx_discrete 定义 labels

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  scale_color_discrete(
    name = "Seasons:", 
    labels = c("Mar—May", "Jun—Aug", "Sep—Nov", "Dec—Feb")
  ) +
  theme(legend.title = element_text(
    family = "Playfair", color = "chocolate", size = 14, face = 2
  ))

image.png

除此之外,我们还可以利用函数,更加方便的对legend 内容进行操作,其实这个我也在[[86-R可视化18-自定义分类或连续数据坐标轴文本]]提过:

代码语言:javascript
复制
p <- ggplot(data = cell_reduction_df) + 
  geom_point(aes(x = UMAP_1, y = UMAP_2, color = cell_anno),
             size = 0.5)
p + scale_color_discrete(
  name = "Seasons:", 
  labels = function(x) {paste0("test", x)}
)

4-移动图例位置

4.1-外围转圈

包括四种:“top”, “right” (which is the default), “bottom”, and “left”:

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  theme(legend.position = "top")

4.2-内嵌图例

之前的是让图例在外围到处溜达,现在让图例进入主图中。

通过调整图例位置legend.position 在0-1 之间,可以将其内嵌:

代码语言:javascript
复制
ggplot(chic,
       aes(x = date, y = temp,
           color = season, shape = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") + theme_classic() + 
  theme(legend.position = c(.15, .15),
        legend.background = element_rect(fill = "transparent"))

element_rect 用来设置非数据类型内容的绘图选项,可以指定图例背景为透明,好看一些:

4.3-调整图例方向

默认下,图例显示是竖直的(自上而下),我们可以将其改变为水平horizontal

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  theme(legend.position = c(.5, .97),
        legend.background = element_rect(fill = "transparent")) +
  guides(color = guide_legend(direction = "horizontal"))

image.png

5-改变图例顺序

其实不只是图例,aes 中设定的属性都可以进行排序。规则是现将排序的列转为因子类型,并对levels 属性进行调整:

代码语言:javascript
复制
chic$season <-
  factor(chic$season,
         levels = c("Winter", "Spring", "Summer", "Autumn"))

ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)")

image.png

6-定义图例标记

guides 函数的color 属性专门设置图例颜色标记,比如标记大小:

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  theme(legend.key = element_rect(fill = NA),
        legend.title = element_text(color = "chocolate",
                                    size = 14, face = 2)) +
  scale_color_discrete("Seasons:") +
  guides(color = guide_legend(override.aes = list(size = 6)))

其中aes 中设置了分类变量,R 会默认设置为guide_legend() :

而连续变量则使用guide_colorbar() :

我们也可以将连续变量修改为分类的样子:

代码语言:javascript
复制
ggplot(chic,
       aes(x = date, y = temp, color = temp)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)", color = "Temperature (°F)") +
  guides(color = guide_legend())

image.png

其他的样式还有:

  • guide_bins()

image.png

  • guide_colorsteps()

image.png

7-自定义图例

除非在aes 中指定变量,否则颜色并不会创建图例,但我们可以借助scale_color_discrete

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = o3)) +
  geom_line(aes(color = "line")) +
  geom_point(aes(color = "points")) +
  labs(x = "Year", y = "Ozone") +
  scale_color_discrete("Type:")

如果想要自定义颜色,其实也可以不在aes 中定义color 属性:

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = o3)) +
  geom_line(color = "darkorange2") +
  geom_point(color = "grey") +
  labs(x = "Year", y = "Ozone") + scale_color_discrete("Type:")

image.png

但是会牺牲掉图例的显示(这里我也没有弄清有什么方便的方法),或者使用函数scale_color_manual

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = o3)) +
  geom_line(aes(color = "line")) +
  geom_point(aes(color = "points")) +
  labs(x = "Year", y = "Ozone") +
  scale_color_manual(name = NULL,
                     guide = "legend",
                     values = c("points" = "darkorange2",
                                "line" = "gray"))

7.1-其他细节

  • 图例标记背景
代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  theme(legend.key = element_rect(fill = "darkgoldenrod1"),
        legend.title = element_text(family = "Playfair",
                                    color = "chocolate",
                                    size = 14, face = 2)) +
  scale_color_discrete("Seasons:")

我们还可以对图例的标记背景进行修改:

  • 图例标记大小
代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  theme(legend.key = element_rect(fill = NA),
        legend.title = element_text(color = "chocolate",
                                    size = 14, face = 2)) +
  scale_color_discrete("Seasons:") +
  guides(color = guide_legend(override.aes = list(size = 6)))

image.png

  • 去除多图交叉的图例标记

默认下,如果是多个图都指定了某个分组:

图例标记也会非常智能的显示的。我们可以不希望显示,在几何对象中使用show.legend = FALSE

代码语言:javascript
复制
ggplot(chic, aes(x = date, y = temp, color = season)) +
  geom_point() +
  labs(x = "Year", y = "Temperature (°F)") +
  geom_rug(show.legend = FALSE)

image.png

  • 个性化图例展示内容

比如我同时设置了图例的color 与fill 元素,制造图标具有背景的效果:

然而图例显示也加了一层外框:

如何去掉这个外框呢?搜了一圈,发现参数:key_glyph 比如:key_glyph = draw_key_rect,就只会画出图例的背景颜色。新问题来了。那么该如何解决tile 图的内部线段呢?

或者这张图也还行?

问题来了

在[[89-R可视化21-利用aplot拼图实现类似热图注释柱效果]] 中我提到过,下面这个图:

这样的好处是,注释柱可以堆叠在一起,比较节约空间;但是,不同类型的色块柱的图例却会“缝合”在一起,产生misunderstanding。

可是我却并没有在ggplot 中找到自行创建这种自定义legend 的方法。看来还是得依托grob 底层啊。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-01-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 北野茶缸子 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 1-移除全部/部分图例
  • 2-移除图例标题
  • 3-改变图例标题和子标签
  • 4-移动图例位置
    • 4.1-外围转圈
      • 4.2-内嵌图例
        • 4.3-调整图例方向
        • 5-改变图例顺序
        • 6-定义图例标记
        • 7-自定义图例
          • 7.1-其他细节
          • 问题来了
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档