首页 文章

如何使用ggplot2向复杂的散点图添加新图例

提问于
浏览
3

我 Build 了一个简单的线性回归模型,并使用该模型产生了一些预测值 . 但是,我更感兴趣的是在图表上可视化它,但我不知道如何添加图例以突出显示原始mpg值'black'和新预测值为"red" .

此示例中使用的数据是来自数据集包的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")

enter image description here

散点图

2 回答

  • 2

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

    # 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"))
    
  • 3

    这是另一种没有 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)
    

相关问题