无法更改ggplot中的行颜色

时间:2017-07-30 16:51:11

标签: r plot ggplot2

我使用ggplot2创建了以下图: enter image description here

现在我希望蓝线是红色虚线,我希望红线是黑线。我使用以下代码来生成图:

ggplot(data=SLLN, aes(x=X1, y=X2, group=1)) + 
  geom_line(aes(colour = "Variable name A")) +                    
  geom_hline(aes(yintercept=theor_price, colour = "Variable name B")) +
  geom_point(size=1) +                       
  scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x), #make log scale
  labels = trans_format("log10", math_format(10^.x))) +
  ylim(175, 250) +                           
  scale_colour_hue(name="", l=30)  +                  
  (lightness=30)
  scale_shape_manual(values=c(22,21)) +     
  scale_linetype_discrete() +
  xlab("xlab") + ylab("ylab") + 
  ggtitle("Title name") +     
  theme_bw()+
  theme(legend.background = element_rect(fill="transparent"), 
  legend.position=c(.85, .7)) 

当我删除geom_line和geom_hline中的aes(),并将颜色的参数更改为“黑色”和“红色”时,这些线条具有我想要的颜色,但它们会从图例中消失?如何保持现在的图像,使用图例,只更改线条的颜色并使水平线虚线?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

aes()函数用于将变量映射到美学属性而不是用于更改geoms的属性,你必须在aes()函数之外指定它们,如下所示:

ggplot(data=SLLN, aes(x=X1, y=X2, group=1)) + 
       geom_line(aes(colour = "Variable name A")) +                    
       geom_hline(aes(yintercept=6, colour = "Variable name B"), linetype="dashed") +
       scale_color_manual(values = c("black","blue")) +
       ... (the rest of your code)