【问题标题】:How to use geom_smooth() on data that is different from the actual plotted data?如何在与实际绘制数据不同的数据上使用 geom_smooth()?
【发布时间】:2013-10-16 03:28:25
【问题描述】:

我有一个使用 ggplot2 的折线图,其中包含三行(在我的数据框中使用变量名称,例如“A”、“B”和“C”)。我想使用method=loess 添加 geom_smooth,但我想添加基于“B”和“C”最小值的回归线。有没有办法做到这一点?

为了说明,这里有一个模拟代码:

names  <- c('n1', 'n2', 'n3', 'n4', 'n5')
aline  <- c(0.18, 0.21, 0.23, 0.20, 0.16)
bline  <- c(0.50, 0.40, 0.30, 0.20, 0.10)
cline  <- c(0.14, 0.20, 0.30, 0.35, 0.33)
min_bc <- c(0.14, 0.20, 0.30, 0.20, 0.10)
df <- data.frame(name, aline, bline, cline)
df.m <- melt(df)
g <- ggplot(df.m, aes(group=1, names, value, colour=variable))
g <- g + geom_line(aes(group=variable))
g <- g + geom_point(aes(colour=variable), alpha=0.4)

我想使用alinemin_bc 添加回归线,而不实际绘制min_bc

另外,我想把这个扔进去: 一般来说,我可能有一些数据,我想使用不同的数据转换来绘制(在同一张图中)不同的线(或点、条等)。是否有任何综合文档可以让我大致了解如何在 R/ggplot 中执行此类操作?

【问题讨论】:

  • 这有点令人困惑。你的意思是你想从aline ~ min_bc(或者相反)绘制回归线?
  • 在任何 ggplot 对象中更改 dataaes(x=..., y=...) 参数。

标签: r plot ggplot2


【解决方案1】:

通常,将与主调用中的绘图相关的数据集设置为ggplot

ggplot(data, aes()) + geom_point()

不过,您也可以为 geom 单独设置数据集:

ggplot(data1, aes()) + geom_point(data = data2)

使用此技术,您可以预先计算要绘制黄土的数据集,并将其提供给geom_smooth()。下面的例子证实了这个假设:

df1 = data.frame(x = 1:100, y = runif(100))
df2 = data.frame(x = 1:100, y = runif(100) + 1)
ggplot(df1, aes(x, y)) + geom_point() + geom_smooth(data = df2)

在此示例中,两个数据集具有相同的列名。如果不是这种情况,您还需要调整aes 中的aes 设置geom_smooth

请记住,绘制另一个数据集的平滑值而不是绘制在它下面的数据集可能会使事情变得非常不清楚。

【讨论】:

  • 我对这个话题还有另一个疑问......如何考虑两个不同的数据帧,其中 ggplot 中使用的一个对象在第二个中不存在(用于创建 geom_smooth 的数据帧)。如果两者都没有所有确切的对象,它将失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 2020-04-11
相关资源
最近更新 更多