控制 ggplot 中非颜色向导的图例元素颜色

7
当使用黑色背景的ggplot2主题时,能否控制图例颜色以指导其他颜色指南,使得图例不会被绘制成黑色?如果可以,怎么做呢?
library(ggplot2) # needs to be 0.9.3 for this theme
data(iris)       # included with ggplot2

theme_black<- function (base_size = 16, base_family = ""){
    theme_minimal() %+replace% 
        theme(
              line = element_line(colour = "white", size = 0.5, linetype = 1, 
                        lineend = "butt"), 
              rect = element_rect(fill = "white", 
                        colour = "white", size = 0.5, linetype = 1), 
              text = element_text(family = base_family, 
                        face = "plain", colour = "white", size = base_size,
                        angle = 0, lineheight = 0.9, hjust = 0, vjust = 0),
              plot.background = element_rect(colour = 'black', fill = 'black'),
              plot.title = element_text(size = rel(1.2)),
              panel.border = element_rect(fill = NA, colour = "white"), 
              panel.grid.major = element_line(colour = "grey20", size = 0.2), 
              panel.grid.minor = element_line(colour = "grey5", size = 0.5),
              strip.background = element_rect(fill = "grey30", colour = "grey30")
             )
    }

ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width, shape=Species,
       colour=Petal.Length))+geom_point()+theme_black()+
       scale_colour_gradient(low = "purple", high = "white")

如您所见,图例形状部分的默认颜色未更改,因此它是不可见的,人们无法确定哪个物种是哪个:

enter image description here

我目前唯一的解决方案是更改图例背景颜色,但这是浪费墨水和丑陋的。


1
这里是部分修复方案:+ guides(shape=guide_legend(override.aes=list(colour="white")))。不幸的是,theme()不能用于更改默认点颜色之类的东西。 - bdemarest
谢谢您的回复(+1)。我认为将其作为答案添加是值得的:我肯定会点赞。 - MattBagg
2个回答

2
简短的回答似乎是没有完美的方法来做到这一点。
我们可以按照@user1317221_G的答案添加带有形状指南的隐藏层,我已经接受了这个方法。但这需要额外的计算量,如果我们保存为pdf,我预计这些隐藏层会存在。
或者,我们可以像@bdemarest在评论中建议的那样覆盖形状指南的颜色。
+ guides(shape=guide_legend(override.aes=list(colour="white"))

但这仍然迫使我们添加特定于主题的代码,而不仅仅是+theme_black()。

我实现了一个稍微复杂一些的版本,因为我根据是否为纸张(灰色/白色背景)或屏幕(黑色背景)制作图形,为会话设置了默认主题。所以我的方法是在会话早期运行类似以下的内容:

 set_theme(theme_black); defaultcol = "white" # for slides
 # or
 set_theme(theme_bw); defaultcol = "black"    # for paper

紧接着是一个包括以下内容的ggplot():

+ guides(shape=guide_legend(override.aes=list(colour=defaultcol))

这样做的好处是最大程度地减少了对特定主题调整图表的需求,但它不如通过主题控制默认ggplot2颜色好。

1
一种方法是添加两个额外的geom_point,逻辑如下:
为图例绘制白色点,用没有图例的黑色点覆盖它们,然后绘制没有图例的彩色点,例如:
geom_point(colour="white",size=1) + 
geom_point(colour="black",size=3,show_guide=FALSE) +
geom_point(show_guide=FALSE)

谢谢回答!(为什么您需要黑色的geom_point,因为顶部的覆盖白色的无论如何?您是否注意到白色显示在边缘的情况?)...... 我希望有一种解决方案,可以在更改主题时不强制我们向代码添加额外的图层。 - MattBagg
是的,我注意到绘制不完整的点覆盖时会出现问题。只要大小不同,就没问题了,也许可以跳过黑色(我想黑色点选项是为了避免在彩色点的点大小上受限制)。 - user1317221_G

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接