ggplot:如何设置所有geoms的默认颜色?

jlh*_*ard 21 r ggplot2

我正在尝试将ggplot中所有geom的默认颜色设置为黑色以外的其他颜色.请注意,这不是关于设置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)
Run Code Online (Sandbox Code Playgroud)

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

编辑: 使用ggplot(df, aes(x=x, color="red"))不是一个选项,因为它使用默认的ggplot调色板(围绕HSL色环均匀分布)创建色阶.只有一种颜色,恰好是浅红色.此外,这会创建一个必须隐藏的图例.#F8766D

met*_*oia 26

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

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)
Run Code Online (Sandbox Code Playgroud)

编辑 如果您想对所有内容执行操作,请使用(从此处编辑借用):

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 
Run Code Online (Sandbox Code Playgroud)

如果要为一个绘图设置默认颜色,只需执行以下操作:

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)
Run Code Online (Sandbox Code Playgroud)

  • 哇,我从来不知道这个功能.惊人. (4认同)
  • @metasequoia 惊人的功能!但是,您的代码存在问题,因为它将颜色美感映射到变量“红色”,尝试将其更改为“绿色”,您会看到线条和点仍然为红色。 (2认同)