gpt4 book ai didi

r - 控制不是ggplot中颜色指南的图例元素的颜色

转载 作者:行者123 更新时间:2023-12-04 12:42:01 28 4
gpt4 key购买 nike

当使用具有黑色背景的 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

我现在唯一的解决方案是更改legend.background 颜色,但这既浪费墨水又丑陋。

最佳答案

简短的回答似乎是没有完美的方法可以做到这一点。

我们可以根据@user1317221_G 的回答添加带有形状指南的隐藏层,我接受了。但这是额外的计算,如果我们保存为 pdf,我希望这些隐藏层会出现。

或者,我们可以覆盖形状指南的颜色,正如@bdemarest 在评论中建议的那样:

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

但这仍然迫使我们在 +theme_black() 之外添加特定于主题的代码

我已经实现了一个稍微复杂的版本,因为我为 session 设置了默认主题,具体取决于我是为纸(灰色/白色背景)还是屏幕(黑色背景)制作绘图。所以我的方法是在 session 的早期按照这些方式运行一些东西:
 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 颜色。

关于r - 控制不是ggplot中颜色指南的图例元素的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999103/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com