【问题标题】:How to add linear lines to a plot with multiple data sets of a data frame?如何将线性线添加到具有数据框多个数据集的绘图中?
【发布时间】:2018-02-21 17:40:14
【问题描述】:

我有以下数据框:

     expected observed group
1: 0.5371429   0.0000     1
2: 1.3428571   1.3736     1
3: 2.6857143   2.4554     1
4: 5.3714286   3.6403     1
5: 0.5294118   0.0000     2
6: 1.3235294   1.1494     2
7: 2.6470588   1.1364     2
8: 5.2941176   4.9774     2
9: 0.5201207   0.0000     3
10: 1.3003018   1.4327    3
11: 2.6006036   2.5918    3
12: 5.2012072   8.0769    3
13: 0.5155039   1.4851    4
14: 1.2887597   1.0638    4
15: 2.5775194   3.1700    4
16: 5.1550388   6.2500    4
17: 0.4976959   0.0000    5
18: 1.2442396   1.2384    5
19: 2.4884793   3.1073    5
20: 4.9769585   4.8148    5

我想根据组散点图每个数据集,所以我有以下代码:

sp <- ggplot(new_df, aes(x = expected, y = observed, colour = group)) + geom_point()

sp + scale_color_gradientn(colours = rainbow(5)) 

并收到以下情节:

我的问题是如何为每个不同的组添加一条直线(截距 = 0,0)? 意思是,最后,我将有 5 条不同颜色的线性线代表同一个图上的每个组。

还有,有没有办法在图例中显示每行的方程式?

【问题讨论】:

  • 你看过geom_abline吗?
  • 它会给出一条直线,而不是每个组
  • 提供一个可重现的例子。另见stackoverflow.com/questions/45624655/…
  • 您可以尝试geom_smooth 的行并使用model 来设置拦截
  • 它也会为所有人提供一行。如何添加 geom_smooth 或 geom_abline 以根据每个组获取多条线?

标签: r ggplot2 regression lm ggpmisc


【解决方案1】:

您可以从ggplot2stat_poly_eqggpmisc 包中使用geom_smooth 获取线性线和方程/R2 文本

    dat <- "expected    observed    group
    0.5371429   0   1
    1.3428571   1.3736  1
    2.6857143   2.4554  1
    5.3714286   3.6403  1
    0.5294118   0   2
    1.3235294   1.1494  2
    2.6470588   1.1364  2
    5.2941176   4.9774  2
    0.5201207   0   3
    1.3003018   1.4327  3
    2.6006036   2.5918  3
    5.2012072   8.0769  3
    0.5155039   1.4851  4
    1.2887597   1.0638  4
    2.5775194   3.17    4
    5.1550388   6.25    4
    0.4976959   0   5
    1.2442396   1.2384  5
    2.4884793   3.1073  5
    4.9769585   4.8148  5
    "  
    library(ggplot2)
    library(ggpmisc)

    df <- read.table(text = dat, header = TRUE)
    df$group <- factor(df$group)

    formula <- y ~ x # needed for ggpmisc's equation and R2 text

    # Put equation & R2 coef to the top left corner
    ggplot(df, aes(expected, observed, colour = group)) +
      geom_point(size = 2, alpha = 0.3) +
      geom_smooth(method = "lm", formula = formula, se = FALSE) +
      stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")), 
                   label.x.npc = "left", label.y.npc = "top",
                   formula = formula, parse = TRUE, size = 4) +
      scale_color_brewer(palette = "Dark2") +
      theme_bw(base_size = 16)

【讨论】:

  • 哇,完美!非常感谢!
  • 没问题!很高兴为您提供帮助!
  • 请再问一个问题,有没有办法在图上只显示 r 平方而没有方程?
  • stat_poly_eq中删除..eq.label..
  • 您知道如何在不更改数据框的情况下更改图例中的文本吗?我想将 1,2,3,4,5 改为不同的字符串
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
相关资源
最近更新 更多