Plotting two scatter plots and regression lines with error bars on same plot using ggplot2 [closed]

StackOverflow https://stackoverflow.com/questions/23524967

  •  17-07-2023
  •  | 
  •  

Pregunta

I am trying to create the following diagram:

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

So far, I have: ggplot(df, aes(x = IOD, y = movement_time, color = cursor, shape = cursor)) but I am not having any luck. Any ideas?

¿Fue útil?

Solución

ggplot2 is my favourite R package, so here is how I would solve this:

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

Otros consejos

This is just a minor riff on @PaulHiemstra's answer, showing how to move the legend inside the plot area, add a border, and get rid of the grey background. IMO ggplot is definitely the way to go.

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

NB: You get the grey background because stat_smooth(...) plots confidence bands by default (which are grey). Setting se=F turns that off.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top