R:使用GGPlot在同一图上绘制两个散点图和带有误差线的回归线

时间:2014-05-07 18:01:23

标签: r plot regression

我正在尝试创建以下图表:

Depicts two different scatter plots on same plot, with different markers and displays each of their linear fits, LSRL in R.

到目前为止,我有:ggplot(df,aes(x = IOD,y = moving_time,color = cursor,shape = cursor))但我没有运气。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

ggplot2是我最喜欢的R包,所以我要解决这个问题:

df = data.frame(difficulty = 2 + (runif(200) * 6),
                ID = rep(c("point", "bubble"), each = 100))
df$movement = rep(c(1.2, 1.4), each = 100) * df$difficulty + (runif(200) / 5)

library(ggplot2)
theme_set(theme_bw())
ggplot(df, aes(x = difficulty, y = movement, color = ID, shape = ID)) + 
    geom_point() + 
    stat_smooth(method = 'lm')

enter image description here

答案 1 :(得分:1)

这只是对@PaulHiemstra的回答的一个小小的重复,展示如何在情节区域内移动图例,添加边框,并摆脱灰色背景。 IMO ggplot绝对是最佳选择。

ggplot(df, aes(x = difficulty, y = movement, color = ID, shape = ID)) + 
  geom_point() + 
  stat_smooth(method = 'lm',se=F)+
  theme(legend.justification=c(1,0), legend.position=c(1,0),
        legend.key=element_rect(color=NA),
        legend.background=element_rect(color="black"))

注意:你得到了灰色背景,因为stat_smooth(...)默认情况下绘制了置信区间(灰色)。设置se=F会将其关闭。