如何制作 ggplot2 趋势线,一条是虚线,另一条是实线?

How do I make ggplot2 trendlines, one dashed and another a solid line?

我希望这张图表上的每条趋势线都具有不同的形状。例如,“男孩”趋势线为虚线,“女孩”趋势线为实线。我在 R 中使用 ggplot2 库。这是我的代码。

dr <- ggplot(Tempdata, 
            aes(x = Tempdata$EffortfulControl,
                y = Tempdata$sqrt_Percent.5, 
                color = Tempdata$Sex1M, 
                shape = Tempdata$Sex1M)) + 
geom_point(aes(shape = Tempdata$Sex1M, 
               color = Tempdata$Sex1M), 
           show.legend = FALSE) + 
scale_shape_manual(values=c(16,17))+ 
geom_smooth(method=lm,se=FALSE,fullrange=TRUE) + 
labs(x = "xaxis label",
     y = "yaxis label", 
     fill = "") +
xlim(3,7) +
ylim(0,10)

dr +  
scale_colour_grey(start = 0.0, 
                  end = .7 , 
                  guide_legend(title = "")) + 
theme_classic() 

根据@nebroth 的建议更新了代码

dr <- ggplot(Tempdata, 
       aes(x=Tempdata$EffortfulControl, 
           y=Tempdata$sqrt_Percent.5, 
           color=Tempdata$Sex1M, 
           shape=Tempdata$Sex1M, 
           linetype=Tempdata$Sex1M)) + geom_point(aes(shape=Tempdata$Sex1M, 
               color=Tempdata$Sex1M), 
           show.legend = FALSE) + 
scale_shape_manual(values=c(16,17))+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE) + 
labs(x="xaxislabel", 
     y = "yaxis label", fill= "") + 
xlim(3,7) + 
ylim(0,10)

dr +  
scale_colour_grey(start = 0.0, 
                  end = 0.4, 
                  guide_legend(title = "")) + 
theme_classic()  

首先回答你的问题: 您可以在 ggplot 中使用 linetype 参数并指定分组: ggplot(data, aes(x=x, y=y, color = z, linetype = z) 如果在 geom_smoothaes 中指定替代数据,也可以在 aes.

中指定

更多提示:通常您不需要在 aes 中再次指定您的对象,您只需提供 colname(例如 ggplot(Tempdata, aes(x=EffortfulControl, y=sqrt_Percent.5, color=Sex1M, shape=Sex1M)))并在绘图的不同层之间放置换行符会有所帮助具有可读性。