gpt4 book ai didi

r - 如何使用 ggplot2 将新图例添加到复杂的散点图

转载 作者:行者123 更新时间:2023-12-01 11:20:24 24 4
gpt4 key购买 nike

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

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

enter image description here

散点图

最佳答案

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

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

关于r - 如何使用 ggplot2 将新图例添加到复杂的散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com