【问题标题】:How do I make ggplot2 trendlines, one dashed and another a solid line?如何制作 ggplot2 趋势线,一条虚线,另一条实线?
【发布时间】:2021-08-19 18:49:17
【问题描述】:

我希望这张图表上的每条趋势线都具有不同的形状。例如,“男孩”趋势线将是虚线,而“女孩”趋势线将是实线。我在 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()  

【问题讨论】:

    标签: r ggplot2 graph data-visualization


    【解决方案1】:

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

    更多提示:一般情况下,您无需在 aes 中再次指定对象,您只需给出列名(例如 ggplot(Tempdata, aes(x=EffortfulControl, y=sqrt_Percent.5, color=Sex1M, shape=Sex1M)) )并在绘图的不同层之间放置换行符有助于提高可读性。

    【讨论】:

    • 谢谢!我尝试在 geom_smooth 中添加您建议的 aes 代码,图表看起来大致相同:``` dr imgur.com/mXoNQYr@nebroth
    • 好的,只有在 aes 中指定数据时才有效。但是您可以在aes 之外指定linetype = "dashed",这应该可以解决问题。我相应地更新了答案。
    • @cellophane_flowers 请在您的答案中仅发布相关代码,很难找到代码的相关部分,尤其是在您的评论中(或按照我的答案建议格式化)。
    • 感谢您的耐心等待和一如既往的支持!我是堆栈溢出的新手。通过您建议的编辑,我的图表现在两条线都为虚线。我怎样才能使一个实心和一个虚线? geom_smooth(method=lm,se=FALSE,fullrange=TRUE, linetype= "dashed") imgur.com/o6sq7zN
    • 从我的代码中删除 guide_legend(title = "")) 修复了它。感谢您在我的代码中添加额外的 cmets。其中大部分是从许多谷歌拼凑而成的。感谢您的宝贵时间!
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多