r - 当填充也用于美学时,ggplot2 更改颜色图例的填充

标签 r ggplot2

当填充也用于 ggplot2 的美学时,有没有办法控制颜色图例的填充?

前任。

dat<-data.frame(id=as.character(1:4), var1=rep(LETTERS[1:2], 2), var2=rep(LETTERS[3:4], 2))
dat
library(ggplot2)

ggplot(dat)+
  geom_bar(aes(id, color=var1, fill=var2))+
  scale_color_manual(values=c("A"="black", "B"="grey"))+
  theme_light()

在这个图例中,很难看到颜色图例中深灰色填充周围的浅灰色边框。我承认指定颜色并在同一个图中填充可能不是一个好习惯,因为很难理解哪种颜色意味着什么,并且填充对象周围的彩色边框很难区分,但我该怎么做如果我想?

Here the background color for the color variable makes it difficult to see the grey outline

通过在图中手动指定填充,可以在未指定填充时控制图例中的填充颜色。
ggplot(dat)+
  geom_bar(aes(id, color=var1), fill="white")+
  theme_light()

enter image description here
我认为有一种方法可以使用主题中的参数来控制它,但是 theme(legend.background=element_rect())控制整个图例的背景(这是正确的)
ggplot(dat)+
  geom_bar(aes(id, color=var1, fill=var2))+
  scale_color_manual(values=c("A"="black", "B"="grey"))+
  theme_light()+
  theme(legend.background = element_rect(fill="blue"))

enter image description here

同样在主题中,theme(legend.key = element_rect(fill="blue"))仅在 var2 周围添加一条细蓝线传说中的盒子,legend.box控制多个图例的排列(“水平”或“垂直”),和 theme(legend.box.background = element_rect(fill="blue"))var1 之间的背景着色和 var2传说。

我认为图例可能使用 NA 的默认值进行填充,因此我尝试使用 scale_color_discrete() 手动指定此值。
ggplot(dat)+
  geom_bar(aes(id, color=var1, fill=var2))+
  scale_color_manual(values=c("A"="black", "B"="grey", 
                              na.translate=TRUE, na.value = "white"))+
  theme_light()

看起来和第一个情节一样。

这似乎应该由 theme() 中的参数控制。或 scale_color_manual ,但我似乎无法弄清楚。
干杯

最佳答案

对于图例的数据相关方面,theme()不会帮你。相反,您需要使用 guides并覆盖颜色图例的填充:

ggplot(dat)+
    geom_bar(aes(id, color=var1, fill=var2))+
    scale_color_manual(values=c("A"="black", "B"="grey"))+
    guides(color = guide_legend(override.aes = list(fill = "white"))) +
    theme_light()

一般规则是 theme()只控制绘图的整体外观,而不是像比例这样的数据相关部分(也许不是“数据相关”,它应该是“根据数据变化的绘图部分”)。

关于r - 当填充也用于美学时,ggplot2 更改颜色图例的填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58089506/

相关文章:

r - 当 x 轴是一个因素时,用 ggplot 添加一条垂直线

r - 地 block 上不需要的元素

r - 检查一个数据框列中的值是否存在于第二个数据框中

r - 如何使用绘图数学表达式自动标记图表轴?

r - 可以从 rvg 结合 openxlsx-Workbook 和 xl_add_vg - 导出可编辑图形

r - 如何绘制带有 NA 条目的线图?

r - mtcars ggplot 不知道如何处理数字类

r - 使用 ggplot 2 创建李克特量表排序图

r - 正如我猜测的那样,在 dplyr 中的另一列上添加新的列基不起作用

r - 如何更改ggboxplot中的x轴标签