Elizabeth
Elizabeth

Reputation: 209

Scatterplot on top of line plot ggplot

Example data:

set.seed(245)
cond <- rep( c("control","treatment"), each=10)
xval <- round(10+ rnorm(20), 1)
yval <- round(10+ rnorm(20), 1)
df <- data.frame(cond, xval, yval)
df$xval[cond=="treatment"] <- df$xval[cond=="treatment"] + 1.5

I would like the "treatment" condition be plotted as a line and the "control" data be plotted as a scatter plot. So far, I have found a work around where I specify them to both be lines but chose that the control line be plotted as 'blank' in scale_linetype_manual:

plot <-ggplot(data=df, aes(x=xval, y=yval, group=cond, colour=cond))+
geom_line(aes(linetype=cond))+
geom_point(aes(shape=cond))+
scale_linetype_manual(values=c('blank', 'solid'))

However, there must be a more straightforward way of plotting the control as a scatter plot and the treatment as a line plot. Eventually, I'd like to remove the geom_point from the treatment line. The way it is now, it would remove the its from the control as well leaving me with nothing for the control.

Any insight would be helpful. Thanks.

Upvotes: 2

Views: 2157

Answers (1)

Henrik
Henrik

Reputation: 67778

I hope I have understood you correctly. You may use a "treatment" subset of the data for geom_line, and a "control" subset for geom_point.

After the subsetting, there is only one "cond" for geom_line ("treatment") and one for geom_point ("control"). Thus, I have removed the aes mapping between "cond" and colour, linetype and shape respectively. You may wish to set these aesthetics to desired values instead. Similarly, no need for group in this solution.

ggplot(data = subset(df, cond == "treatment"), aes(x = xval, y = yval)) +
  geom_line() +
  geom_point(data = subset(df, cond == "control"))

enter image description here

Update following comment from OP, "Now, what if my data had actually three "conditions" where 2 of the conditions would be plotted as lines and the other 1 is scatterplot."

# some data
set.seed(123)
cond <- rep( c("contr","treat", "post-treat"), each = 10)
xval <- rnorm(30)
yval <- rnorm(30)
df <- data.frame(cond, xval, yval)

# plot
ggplot(data = subset(df, cond %in% c("treat", "post-treat")), aes(x = xval, y = yval)) +
         geom_line(aes(group = cond, colour = cond)) +
         geom_point(data = subset(df, cond == "contr"))

enter image description here

Upvotes: 2

Related Questions