两个回归方程ggplot r的位置

问题描述 投票:0回答:1

我有3个变量。 x =年龄,y =消费得分和性别(男女)。我想查看每种性别的关系b / w y和x。我有一个散点图,其中有两个回归线,一个用于女性,一个用于男性:公式= y〜x,方法=“ lm”。我想将两个回归方程放在图上,但是这些方程在其默认位置(左上角)很难读取。所以我需要将两个回归方程的位置更改为右上角。但是,当我尝试将两个方程式叠加在一起时,它们又很难读懂。请帮忙!谢谢!

x <- df$age
y <- df$spending_score


formula <- y ~ x


k <- ggplot(df, aes(age, spending_score, color = gender)) +
  geom_point() +
  labs(x = "Age", y = "Spending score", title = "Spending score vs. age") +
  stat_smooth(aes(fill = gender, color = gender), method = "lm", formula = formula) +
  stat_regline_equation(
    label.x = 50, label.y = 80,
    aes(label =  paste(..eq.label.., ..rr.label.., sep = "~~~~")),
    formula = formula
    ) +
  theme_classic2() +
  theme(plot.title = element_text(hjust = 0.5))
ggpar(k, palette = "jco")

enter image description here

r ggplot2 linear-regression
1个回答
0
投票

您只为label.x和label.y提供1个值,所以所有文本都占据该位置。如果您有两行或更多行,则需要提供一个长为[]的向量

library(ggplot2)
library(ggpubr)
F = as.formula("y~x")
ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Species)) +
geom_point() +
stat_smooth(aes(fill = Species, color = Species), method = "lm", formula = F) +
stat_regline_equation(
          label.x = c(6,6,6), label.y = c(4,4.25,4.5),
          aes(label =  paste(..eq.label.., ..adj.rr.label.., sep = "~~~~")),
          formula=F,size=3
)

要详细说明,在此数据集中,虹膜中的物种具有3种级别:setosa,versicolor和virginica。当我指定label.x和label.y时,第一个值用于setosa,即x = 6,y = 4,对于杂色,x = 6,y = 4.25,依此类推。]

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.