gpt4 book ai didi

r - ggplot : How to set default color for all geoms?

转载 作者:行者123 更新时间:2023-12-03 11:54:55 27 4
gpt4 key购买 nike

我正在尝试将 ggplot 中所有几何图形的默认颜色设置为黑色以外的颜色。请注意,这不是关于设置 scale_color ...

简单的例子:

# linear model with confidence bands...
set.seed(1)
df <- data.frame(x=1:50, y=5 + 2*(1:50)+rnorm(50,sd=10))
lm <- lm(y~x,df)
se <- summary(lm)$sigma # standard error of fit
Z <- qnorm(0.05/2,lower.tail=F) # 95% confidence bands
df <- cbind(df,predict(lm,se.fit=T)[c("fit","se.fit")])
# plot the result...
library(ggplot2)
ggplot(df, aes(x=x)) +
geom_point(aes(y=y), size=3) +
geom_line(aes(y=fit)) +
geom_line(aes(y=fit+Z*se.fit), linetype=2)+
geom_line(aes(y=fit-Z*se.fit), linetype=2)



现在,假设我想让一切都变成红色。撇开这样做的可取性不谈,我认为 ggplot(df, aes(x=x), colour="red")会做的。但是 colour=参数似乎被忽略了:一切仍然是黑色的。我可以加 colour="red"到每个 geom_打电话,但我试图避免这种情况。

编辑:
使用 ggplot(df, aes(x=x, color="red"))不是一个选项,因为它使用默认的 ggplot 调色板( evenly spaced around an HSL color circle )创建色标。用一种颜色,这是 #F8766D ,恰好是浅红色。此外,这会创建一个必须隐藏的图例。

最佳答案

您可以通过以下方式为每种几何类型设置默认颜色:

update_geom_defaults("point",   list(colour = "red"))
update_geom_defaults("line", list(colour = "red"))

ggplot(df, aes(x=x)) +
geom_point(aes(y=y), size=3) +
geom_line(aes(y=fit)) +
geom_line(aes(y=fit+Z*se.fit), linetype=2)+
geom_line(aes(y=fit-Z*se.fit), linetype=2)

编辑
如果您想对所有内容进行操作,请使用(编辑来自 here 的借用):
params <- ls(pattern = '^geom_', env = as.environment('package:ggplot2'))
geoms <- gsub("geom_", "", params)

lapply(geoms, update_geom_defaults, list(colour = "red"))
lapply(geoms, update_geom_defaults, list(fill = "red", colour = "red")) ## include fills

如果您想为一个图设置默认颜色,只需执行以下操作:
ggplot(df, aes(x=x, colour="red")) + 
geom_point(aes(y=y), size=3) +
geom_line(aes(y=fit)) +
geom_line(aes(y=fit+Z*se.fit), linetype=2)+
geom_line(aes(y=fit-Z*se.fit), linetype=2)

关于r - ggplot : How to set default color for all geoms?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21174625/

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