【问题标题】:How to add new legends to complicated scatter plot using ggplot2如何使用 ggplot2 将新图例添加到复杂的散点图中
【发布时间】:2017-11-16 03:22:06
【问题描述】:

我建立了一个简单的线性回归模型,并使用该模型生成了一些预测值。但是,我对在图表上可视化它更感兴趣,但我不知道如何添加图例以将原始 mpg 值突出显示为“黑色”和新的 predicted 值作为“红色”。

本例中使用的数据是 datasets 包中的 mtcars 数据集

    library(ggplot2)

    library(datasets)
    library(broom)

    # Build a simple linear model between hp and mpg

    m1<-lm(hp~mpg,data=mtcars)

    # Predict new `mpg` given values below 

    new_mpg = data.frame(mpg=c(23,21,30,28))

    new_hp<- augment(m1,newdata=new_mpg)

    # plot new predicted values in the graph along with original mpg values

    ggplot(data=mtcars,aes(x=mpg,y=hp)) + geom_point(color="black") + geom_smooth(method="lm",col=4,se=F) + 
      geom_point(data=new_hp,aes(y=.fitted),color="red") 

散点图

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    这是一个想法。您可以将预测数据和观察数据组合在同一数据框中,然后创建散点图以生成图例。以下代码是您现有代码的扩展。

    # Prepare the dataset
    library(dplyr)
    
    new_hp2 <- new_hp %>%
      select(mpg, hp = .fitted) %>%
      # Add a label to show it is predicted data
      mutate(Type = "Predicted")
    
    dt <- mtcars %>%
      select(mpg, hp) %>%
      # Add a label to show it is observed data
      mutate(Type = "Observed") %>%
      # Combine predicted data and observed data
      bind_rows(new_hp2)
    
    # plot the data
    ggplot(data = dt, aes(x = mpg, y = hp, color = factor(Type))) + 
      geom_smooth(method="lm", col = 4, se = F) +
      geom_point() +
      scale_color_manual(name = "Type", values = c("Black", "Red"))
    

    【讨论】:

    • 几乎与我即将发布的“单线”相同:) mtcars %&gt;% select(mpg, .fitted = hp) %&gt;% mutate(predicted = 0) %&gt;% bind_rows(mutate(new_hp, predicted = 1)) %&gt;% ggplot(aes(mpg, .fitted)) + geom_point(aes(color = as.factor(predicted))) + geom_smooth(method = "lm", se = FALSE) + scale_color_manual(values = c("black", "red"), name = "predicted") + labs(y = "hp")
    • @neilfws 我喜欢你的“单线”。感谢分享。
    • 感谢您分享您的代码。非常感谢您的帮助
    【解决方案2】:

    这是不使用dplyr 的另一种方法:

    ggplot() + 
      geom_point(data = mtcars, aes(x = mpg, y = hp, colour = "Obs")) +
      geom_point(data = new_hp, aes(x = mpg, y = .fitted, colour = "Pred")) +
      scale_colour_manual(name="Type",  
                          values = c("black", "red")) +
      geom_smooth(data = mtcars, aes(x = mpg, y = hp),
                  method = "lm", col = 4, se = F)
    

    【讨论】:

    • 非常感谢@AK88。它真的帮助我拓宽了我的 R 技能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2019-05-08
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多