【问题标题】:trendline in R in ggplotggplot中R中的趋势线
【发布时间】:2020-12-28 17:23:44
【问题描述】:
mpg %>% 
  mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
  ggplot(aes(displ, hwy, colour = Color)) + 
  geom_point() + 
  scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000"))

为此,我尝试添加适用于所有类别的趋势线,因为如果我添加趋势线 geom_smooth(method="lm"),它会分别绘制 2 个座位,这是我不想要的

【问题讨论】:

    标签: r trendline


    【解决方案1】:

    在对geom_smooth 的调用中使用group = 1 覆盖colour 美学,这是分组美学。

    library(tidyverse)
    
    mpg %>% 
      mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
      ggplot(aes(displ, hwy, colour = Color)) + 
      geom_point() + 
      scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000")) +
      geom_smooth(aes(group = 1),
                  method = "lm", formula = y ~ x)
    

    【讨论】:

      【解决方案2】:

      geom_smooth 从 ggplot 继承 aes 参数。您可以将“颜色”移动到 geom_point,或将 inherit.aes = F 传递给 geom_smooth。

      mpg %>% 
        mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
        ggplot(aes(displ, hwy)) + 
        geom_point(aes(, colour = Color)) + 
        scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000"))  + geom_smooth(method = 'lm')
      
      #or:
      mpg %>% 
        mutate(Color=ifelse(class=='2seater','2seater','Other')) %>% 
        ggplot(aes(displ, hwy, colour = Color)) + 
        geom_point() + 
        scale_color_manual(values = c("2seater" = "#992399", "Other" = "#000000")) + geom_smooth(method = 'lm', inherit.aes = F, aes(displ, hwy))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多