【问题标题】:Overlapping Trend Lines in scatterplots, R散点图中的重叠趋势线,R
【发布时间】:2016-07-31 23:58:49
【问题描述】:

我正在尝试使用 R 中的 geom_smooth() 覆盖多条趋势线。我目前有此代码。

ggplot(mtcars2, aes(x=Displacement, y = Variable, color = Variable))
+ geom_point(aes(x=mpg, y = hp, col = "Power")) 
+ geom_point(aes(x=mpg, y = drat, col = "Drag Coef."))

(mtcars2 是 mtcars 的规范化形式)

这给了我这张图表。

我正在尝试使用 geom_smooth(method='lm') 为这两个变量绘制两条趋势线。有什么想法吗?

(奖励:如果可能,我还想实现 'shape=1' 参数来区分变量。以下方法不起作用)

geom_point(aes(x=mpg, y = hp, col = "Power", shape=2))

更新 我设法做到了。

ggplot(mtcars2, aes(x=Displacement, y = Variable, color = Variable)) 
+ geom_point(aes(x=disp, y = hp, col = "Power")) 
+ geom_point(aes(x=disp, y = mpg, col = "MPG")) 
+ geom_smooth(method= 'lm',aes(x=disp, y = hp, col = "Power"))
+ geom_smooth(method= 'lm',aes(x=disp, y = mpg, col = "MPG"))

看起来像这样。

但这是一段丑陋的代码。如果有人能让这段代码看起来更漂亮,那就太好了。另外,我还不能实现 'shape=2' 参数。

【问题讨论】:

  • mtcars2mtcars 有何不同?
  • 我对整个数据集进行了标准化。相应地更新了问题。

标签: r ggplot2 scatter-plot lm


【解决方案1】:

您的生活似乎比需要的更艰难...您可以将其他参数传递给aes(),例如groupshape

我不知道你的标准化是否正确,但这应该足以让你朝着正确的方向前进:

library(ggplot2)
library(reshape2)

#Do some normalization
mtcars$disp_norm <- with(mtcars, (disp - min(disp)) / (max(disp) -  min(disp)))
mtcars$hp_norm <- with(mtcars, (hp - min(hp)) / (max(hp) -  min(hp)))
mtcars$drat_norm <- with(mtcars, (drat - min(drat)) / (max(drat) -  min(drat)))

#Melt into long form
mtcars.m <- melt(mtcars, id.vars = "disp_norm", measure.vars = c("hp_norm", "drat_norm"))

#plot
ggplot(mtcars.m, aes(disp_norm, value, group = variable, colour = variable, shape = variable)) +
  geom_point() +
  geom_smooth(method = "lm")

产量:

【讨论】:

  • 谢谢!那行得通!但是,我想要一种方法,我可以专门选择要使用的列,而无需创建新表。 (我知道我很挑剔,但我正在尽量减少代码)
  • @krthkskmr - 如果需要,您可以在对 ggplot() 的调用中嵌入 melt() 函数。然后您需要相应地修改measure.vars。但是,99% 的 ggplot 示例都以调用 melt()... 开头是有原因的,这是因为您通常需要对数据进行一些预处理以将其转换为 ggplot2 友好格式。
  • @krthkskmr - 另外,计算机内存很便宜,编写过于密集的代码并不是...有时分步分解会更好:)
  • @krthkskmr - 如果这回答了您的问题,您能否打勾,以便其他读者知道这符合您的需求?谢谢!
猜你喜欢
  • 2021-07-04
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
相关资源
最近更新 更多