1
votes

I have two different datasets which I'd like to plot in the same ggplot2 plot, using different geoms for each. Ideally I would also like a legend which shows that the point geom corresponds to one type of data and the line geom corresponds to the other, but I cannot figure out how to do this. An example of what my data basically looks like is below, minus the legend.

require(ggplot2)

set.seed(1)

d1 = data.frame(y_values = rnorm(21), x_values = 1:21, factor_values = as.factor(sample(1:3, 21, replace=T)))
d2 = data.frame(y_values = seq(-1,1,by = .05), x_values = seq(1,21,by = .5))



ggplot() + 
geom_point(data=d1, aes(x=x_values, y=y_values, color=factor_values)) + 
geom_line(data=d2, aes(x = x_values, y=y_values), color="blue")
1

1 Answers

1
votes

Maybe is this what you want? Two legends for each data. You can enable linetype in order to create a new legend so that points and lines can be in different places:

#Code
ggplot() + 
  geom_point(data=d1, aes(x=x_values, y=y_values, color=factor_values)) + 
  geom_line(data=d2, aes(x = x_values, y=y_values,linetype='myline'), color="blue")+
  scale_linetype_manual('My line',values='solid')

Output:

enter image description here

Or you can also try this:

#Code 2
ggplot() + 
  geom_point(data=d1, aes(x=x_values, y=y_values, color=factor_values)) + 
  geom_line(data=d2, aes(x = x_values, y=y_values,linetype='myline'), color="blue")+
  scale_linetype_manual('',values='solid')+
  theme(
    legend.spacing = unit(-17,'pt'),
    legend.margin = margin(t=0,b=0,unit='pt'),
    legend.background = element_blank()
  )+guides(linetype=guide_legend(title="New Legend Title"),
         color=guide_legend(title=""))

Output:

enter image description here