繁体   English   中英

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

[英]How to add new legends to complicated scatter plot using ggplot2

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

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

在此输入图像描述

散点图

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM