BenO - 10 months ago 65

R Question

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.

`Bank01MWtest<-data.frame(X=(c(1,2,2,1)),variable=(c("MW-01A","MW-01A","MW-01B","MW-01B")),value=(c(576,571,584,580)))`

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.

Any help?

Answer Source

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.

```
library(ggplot2)
library(reshape2)
Bank01MWtest<-data.frame(X=sample(c(1,1,2,2)),
variable=sample(c("MW01A","MW01A","MW01B","MW01B")),
value=sample(c(576,571,584,580)))
### 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")) +
coord_cartesian(ylim=c(570,590))
```