【问题标题】:How to automatically combine two ggplot legends into one with labels from a third variable如何使用来自第三个变量的标签自动将两个 ggplot 图例组合成一个
【发布时间】:2020-03-19 18:14:51
【问题描述】:

我想用颜色和形状美学绘制数据。这很好用,但是我正在努力制作一个不错的传奇。

这是一个使用 mtcars 数据集的 MWE。数据操作对于重新处理我正在处理的数据集是必要的。变量 cylindex 是人工创建的,以允许在圆柱编号上进行颜色填充,并为该类别中的每个观测值具有不同的形状。变量 car 是我理想的用作图例标签的对象。

library(tidyverse)
library(plotly)

data(mtcars)
mtcars <- mtcars[c(1,3,4,5,8,30),c("cyl","disp","hp")] %>% 
  as_tibble(rownames="car") %>%
  group_by(cyl) %>% 
  mutate(cylindex=rank(cyl,ties.method="first")) %>%
  ungroup() %>%
  # removed because 'car' is available from the row name
  # but this was used in the original question and one answer
  #mutate(brand=letters[1:nrow(.)]) %>% 
  mutate_at(c("cyl","cylindex"),as_factor) %>%
  mutate(legend=paste(cyl,cylindex,sep=" - "))

mtcars %>% 
  ggplot(aes(x=disp, y=hp, color=cyl, shape=cylindex)) +
  geom_point(size=10) -> g
print(g)
ggplotly(g)

mtcars %>% 
  ggplot(aes(x=disp, y=hp, color=legend, shape=legend)) +
  geom_point(size=10) +
  scale_color_manual(values=c("red","red","blue","blue","blue","green")) + 
  scale_shape_manual(values=c(16,17,16,17,15,16))

ggplot2 正在生成以下内容:

使用 ggplotly 至少结合了图例,但是我很难将标签自动更改为相应的汽车。

使用来自@dc37 的答案,我设法生成了类似于 ggplotly 的图例,但以硬编码的方式。我在每个条目旁边写下了我想要的图例标签。该信息来自从行名称添加的汽车列。

我该怎么做

- 将两个图例与 ggplot2 结合(类似于 ggploty),无需对数据量进行硬编码

- 将图例标签自动更改为另一个变量中的值(本例中为品牌)

非常感谢您的帮助。

【问题讨论】:

标签: r ggplot2 legend


【解决方案1】:

为了组合图例,您可以创建一个将两个变量组合在一起的新分类列:

mtcars %>% 
  filter(as.numeric(cylindex)<=2) %>%
  mutate(Legend = paste(cyl,cylindex, sep = ",")) %>% 
  ggplot(aes(x=disp, y=hp, color=Legend, shape=Legend)) +
  geom_point(size=10) +
  scale_color_manual(values = rep(c("red","blue","green"), each = 2))+
  scale_shape_manual(values = rep(c(16,18),3))

如果您想将品牌变量作为标签,只需在您的aes 中使用brand

mtcars %>% 
  filter(as.numeric(cylindex)<=2) %>%
  ggplot(aes(x=disp, y=hp, color=brand, shape=brand)) +
  geom_point(size=10) +
  scale_color_manual(values = rep(c("red","blue","green"), each = 2))+
  scale_shape_manual(values = rep(c(16,18),3))

或使用scale_color_manualscale_shape_manual,您可以将新“传奇”变量的每个级别与“品牌”值相关联:

mtcars %>% 
  filter(as.numeric(cylindex)<=2) %>%
  mutate(Legend = paste(cyl,cylindex, sep = ",")) %>% 
  ggplot(aes(x=disp, y=hp, color=Legend, shape=Legend)) +
  geom_point(size=10) +
  scale_color_manual(values = rep(c("red","blue","green"), each = 2), 
                     labels = c(`6,1` = "a",`6,2` = "b", `4,1` = "c",`4,2` = "h",`8,1` = "e", `8,2` = "g"))+
  scale_shape_manual(values = rep(c(16,18),3),
                     labels = c(`6,1` = "a",`6,2` = "b", `4,1` = "c",`4,2` = "h",`8,1` = "e", `8,2` = "g"))

它回答了你的问题吗?

【讨论】:

  • 感谢您的回答。解决方案 1 和 3 是正确的,而直接使用品牌会混淆色标(c 和 e 都是蓝色,尽管来自不同的 cyl 类别)。我通过每个气缸类别恰好有 2 个条目使示例变得简单,但我实际上正在寻找一种灵活的方法,因为数字可以改变。我将相应地更改示例。
猜你喜欢
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多