【问题标题】:Position of two regression equations ggplot r两个回归方程ggplot r的位置
【发布时间】:2019-11-24 22:03:34
【问题描述】:

我有 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")

【问题讨论】:

    标签: r ggplot2 linear-regression


    【解决方案1】:

    您只为 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,对于 versicolor,x=6,y=4.25 等等。

    【讨论】:

    • 很高兴它对您有所帮助。我仍然不时犯愚蠢的错误:)
    • 是否有一种简洁的编程方式来指定label.y 向量的合理数字?
    • @MarkNeal,在这种情况下,max(iris$Sepal.Width) + seq(0,length.out=3,by=diff(range(iris$Sepal.Width))/10)还是沿着这条线?
    • 我在 ggpubr 提出了一个 github 问题,该问题处理图表上多个统计结果的相关位置问题。
    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2023-01-09
    • 2023-03-13
    • 1970-01-01
    • 2019-11-01
    相关资源
    最近更新 更多