在ggplot2中控制水平线颜色

12

请问有没有人能告诉我这个脚本出了什么问题? 我需要两条水平、黑色、虚线,但我得到了两条红色连续的线。 尽管使用了theme_bw,但我也无法将图形边距的颜色更改为黑色,并且箱线图的填充颜色也不是灰色所需的颜色。

  dat1 <- data.frame (xvar = rep(c("A", "B"), each=10),

                yvar = 1:20 + rnorm(20,sd=3))

  ggplot(dat1, aes(x=xvar, y=yvar)) +
  theme_bw()+
  geom_boxplot(fill=grey)+
  geom_hline(aes(yintercept=40, color="black", linetype="dashed"))+
  geom_hline(aes(yintercept=33.84, color="black", linetype="dashed"))+  
  scale_x_discrete(name="") +
  scale_y_continuous(name="temperature (°C)")+
  opts(
    panel.grid.major = theme_line(size = 0.5, colour = NA),
    panel.background = theme_rect(colour = NA),   
    axis.title.y = theme_text(angle=90,face="bold", colour="black", size=14),
    axis.text.y  = theme_text(face="bold",angle=0, size=14,colour="black"),
    axis.title.x = theme_text(face="bold", colour="black", size=14),
    axis.text.x  = theme_text( size=14,vjust=1.2, colour=NA))

非常感谢!

1个回答

24

关于黑色虚线,你应该在aes()之外定义它。尝试下面的代码:

geom_hline(aes(yintercept=40), color="black", linetype="dashed")

关于箱线图,您应该将代码更正为以下内容:

geom_boxplot(fill="gray")

最后,想要得到黑色边缘,请注意在opts(..., panel.background = theme_rect(colour = NA),...)中将边缘设置为NA颜色。为了解决这个问题,请尝试以下方法:

panel.background = theme_rect(colour = "black")

希望我的评论能够帮到你。


非常感谢Sepehr!之前没有回答是因为我停止在我的Gmail账户中接收答案了。它确实起作用了。 - Agus camacho
如果我想根据 aes 因子(例如 boxplot 颜色分组)对线条进行着色怎么办?geom_hline() 似乎不能接受多个 aes 语句。 - jzadra

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