BenO BenO - 10 days ago 4x
R Question

R - ggplot2 geom_area only one category visible?

New to R, new to stackoverflow, so forgive me....

I'm trying to do a timeseries plot in R using ggplot2. I want to show two line graphs which are filled below their value for a given date. I've been trying to do this with the geom_area(position="identity") function.

However, only one color shows up on my graph (though both show in the legend). I started by melting my data using melt() and am now working with three columns (X=time, variable=groundwater well, value=groundwater elevation). Below is a simplified version of my code, and a screenshot at what I get.


ggplot(data=Bank01MWtest, aes(x=X, y=value,group=variable))+geom_area(position="identity", aes(fill=variable))+geom_line(aes(color=variable))+coord_cartesian(ylim=c(570,590))

I want to show two colors. One color below MW.01A line and one below MW.01B line.

Elevation Data

Updated to be reproducible

Any help?


I believe geom_area is being replaced by geom_ribbon in ggplot2, so I'll use the latter in my solution. You'll also need to restructure your data from long to wide for this solution, giving each of the legend categories their own column. I'll do this with the dcast function within the reshape2 package.

The idea here is to add layers with different ymax variables, assign legend labels with the fill option, and then add a legend with colors using the scale_fill_manual function.



### Note above I modified your category labels by getting rid of the "-" sign 
### so that they can be used as variable names below.

dat = dcast(Bank01MWtest, X~variable)

ggplot(data=dat, aes(x=X)) + 
  geom_ribbon(aes(ymin=0, ymax=MW01A, fill="MW01A")) + 
  geom_ribbon(aes(ymin=0, ymax=MW01B, fill="MW01B")) +
  scale_fill_manual("", values=c("green", "blue")) +