4
votes

I have two area plots (call them 'blue' and 'green') where the green is mostly under the blue plot, but on a very few points, it is higher than the blue plot. I want to use transparency say alpha = 0.2 for both, and also be able to specify the colors for each. My problem now is that since the green plot is mostly under the blue plot, its area mostly has the blended color blue + green = some other color, and in only a few places shows its "true" green color. However the legend of course shows the blue plot mapped to blue and the green plot mapped to green. Problem is, when someone looks at the graph, they will be confused since the green plot mostly looks non-green (because it's overlapping with blue most of the time).

Here's my code (super simplified version of my real application).

df <- data.frame( date = 1:5, blue = 10, green = c(1,5,11,5,1))
df.m <- melt( df, id = 'date', variable_name = 'type' )
df.m$type <- ordered( df.m$type, c('green', 'blue'))

ggplot(df.m, aes(date,value)) +
  geom_area( aes(fill = type),  position = 'identity', alpha = 0.2) +
  scale_fill_manual ( values = c('green', 'blue') )

enter image description here

As you can see, the "true green" area of the green plot is very small, so the legend color for green doesn't really match the majority of the green plot. This is of course the right behavior by design, but I am wondering if there is some way I can get the legend colour for green, and the overlapping blue+green color to match up. One thing I did try is to transform the blue variable to blue - green, and then make the area plots stacked (with position = "stack"). This almost works but isn't quite satisfactory because the color on the dates where the new blue variable is negative looks strange.

Are there other ways to get the legend color for green and the color of the "overlapping blue/green" area to match up? Maybe a way to directly specify the legend color? Any help appreciated!

1
Didn't you try to choose other colors? %)ulidtko

1 Answers

2
votes

I do not think defining custom colors in the legend is possible with a simple call in ggplot2, but if you do insist on specifying the colors, you might draw the plot without a legend by opts(legend.position = "none") and attach a separate legend by eg. using grid viewport. Package gridExtra could also be a great resource for the latter task.