I cannot replicate the OP's error, so I'm guessing the question is: "How to add a legend with separate geom
elements?"
2 approaches here:
- Basic: one dataset, legend from aes()
- Advanced: customized
legend keys (copied almost directly from the linked answer).
First, it's usually good practice to send a single dataset into ggplot and add grouping variables as their own columns. Set your desired properties based on these groupings (i.e. colour, fill, size, shape, alpha). ggplot will construct a legend based on these grouping variables. (Note: A single data.frame isn't necessary for this specific case because you are already subsetting your data to make different geoms
.)
#Example data
conc <- c(0.004, 0.003, 0.003, 0.003, 0.004, 0.003, 0.004, 0.008, 0.020)
time <- c(seq(from=1,to=length(conc)))
data1 <- data.frame(time,conc)
conc <- c(0.007, 0.012, 0.002, 0.003, 0.003, 0.004, 0.007, 0.003, 0.004,
0.005, 0.004, 0.016)
time <- c(seq(from=1,to=length(conc)))
data2 <- data.frame(time,conc)
#Create grouping variables
data1$category <- "myPoint"
data2$category <- "myStep"
data3 <- rbind(data1, data2)
Basic approach:
#Graph the combined data, setting the overall aes()
#but subset the data for the different visual elements (points and steps)
ggplot(data3, aes(time, conc, colour=category))+ coord_cartesian(ylim = c(0,0.075))+
geom_point(data=data3[data3$category == "myPoint",], shape=10,size=2)+
geom_step( data=data3[data3$category == "myStep", ], size=1)+
xlab("Sampling Time (sec)")+
ylab("Concentration (#/cm^3)") +
ggtitle("Basic")
Advanced approach:
#Specify a custom colour in each variable's aesthetics
#Hack the legend: color = guide_legend(override.aes = list(...))
ggplot()+ coord_cartesian(ylim = c(0,0.075))+
geom_point(data=data1,aes(time,conc, color='point'),shape=10,size=2)+
geom_step(data=data2,aes(time,conc, color='step'),size=1)+
xlab("Sampling Time (sec)")+
ylab("Concentration (#/cm^3)") +
ggtitle("Advanced") +
scale_colour_manual(name = "legend",
values = c("point" = "black", "step" = "black")) +
guides(color=guide_legend(override.aes=list(
shape=c(10, NA),
linetype=c(0,1)
)))
dput(spAm)
etc. might be useful. – lukeArbind
). – oshundata2$category <- "myStep"). You can assign colors, shapes, transparency according to the different groupings. I cannot replicate your error but I'm guessing you are setting
aes` for one dataset but trying to plot both? – oshun