英文:
How to plot two regressions lines in one plot: two x and 1 y using R
问题
如何在一个图中使用ggplot
或其他函数将线性模型Number ~ Spending和Number ~ Score的回归线绘制在一起,以可视化这两条线的斜率差异?
英文:
I have a data set called "Data" as following:
Spending | Score | Number |
---|---|---|
100 | 2 | 5 |
200 | 26 | 89 |
1000 | 90 | 65 |
How can I put the regression lines of linear model Number ~ Spending and Number ~ Score in one plot either use ggplot
or other functions? I would like to visualize the difference of slopes in this plot.
答案1
得分: 2
作为一个 ggplot2
的方法,你可以使用多个 geom_smooth
来为数据的多列添加回归线:
dat <- structure(list(
Spending = c(100L, 200L, 1000L),
Score = c(2L, 26L, 90L),
Number = c(5L, 89L, 65L)
), class = "data.frame", row.names = c(NA, -3L))
library(ggplot2)
ggplot(dat, aes(y = Number)) +
geom_smooth(aes(x = Spending, color = "Spending"),
method = "lm"
) +
geom_smooth(aes(x = Score, color = "Score"),
method = "lm"
)
#> `geom_smooth()` using formula = 'y ~ x'
#> `geom_smooth()` using formula = 'y ~ x'
第二种方法是使用 tidyr::pivot_longer
将数据重塑成长格式,这样你可以只使用一个 geom_smooth
来达到相同的效果:
dat <- structure(list(
Spending = c(100L, 200L, 1000L),
Score = c(2L, 26L, 90L),
Number = c(5L, 89L, 65L)
), class = "data.frame", row.names = c(NA, -3L))
library(ggplot2)
dat |>
tidyr::pivot_longer(-Number) |>
ggplot(aes(x = value, y = Number, color = name)) +
geom_smooth(method = "lm")
#> `geom_smooth()` using formula = 'y ~ x'
<!-- -->
英文:
As a ggplot2
approach you could use multiple geom_smooth
to add regression lines for multiple columns of your data:
dat <- structure(list(
Spending = c(100L, 200L, 1000L),
Score = c(2L, 26L, 90L),
Number = c(5L, 89L, 65L)
), class = "data.frame", row.names = c(NA, -3L))
library(ggplot2)
ggplot(dat, aes(y = Number)) +
geom_smooth(aes(x = Spending, color = "Spending"),
method = "lm"
) +
geom_smooth(aes(x = Score, color = "Score"),
method = "lm"
)
#> `geom_smooth()` using formula = 'y ~ x'
#> `geom_smooth()` using formula = 'y ~ x'
<!-- -->
A second approach would be to reshape your data to long using e.g. tidyr::pivot_longer
which allows to get the same result with just one geom_smooth
:
dat <- structure(list(
Spending = c(100L, 200L, 1000L),
Score = c(2L, 26L, 90L),
Number = c(5L, 89L, 65L)
), class = "data.frame", row.names = c(NA, -3L))
library(ggplot2)
dat |>
tidyr::pivot_longer(-Number) |>
ggplot(aes(x = value, y = Number, color = name)) +
geom_smooth(method = "lm")
#> `geom_smooth()` using formula = 'y ~ x'
<!-- -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论