R / ggplot2: how to combine legend and plot colors in overlapping sections?

I have two sections (call them “blue” and “green”), where green is mostly under the blue graph, but at very few points it is larger than the blue graph. I want to use transparency: alpha = 0.2 for both, and also be able to specify colors for each. My problem is that since the green graph is mostly under the blue graph, its area is basically a mixed color blue + green = some other color, and only in a few places does its “true” green color appear. However, of course, the legend shows a blue graph displayed on blue and a green graph displayed on green. The problem is that when someone looks at the chart, they will be confused, since the green chart basically looks green (because it overlaps the blue most of all).

Here is 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 graph is very small, so the color of the legend for green does not actually match most of the green graph. This, of course, is the correct design behavior, but I wonder if there is a way to get the legend color for green , and the matching blue+green color is a match. One thing I tried to do was convert the blue variable to blue - green , and then group the parts of the area (using position = "stack" ). This almost works, but not entirely satisfactory, because the color on 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 matching blue / green region? Maybe a way to directly indicate the color of the legend? Any help appreciated!

+4
colors r ggplot2
Feb 13 2018-11-11T00:
source share
1 answer

I do not think that defining custom colors in a legend is possible with a simple call to ggplot2, but if you insist on specifying colors, you can draw a story without the opts(legend.position = "none") legend opts(legend.position = "none") and attach a separate legend for example. using the grid. The gridExtra package can also be a great resource for the latter task.

+2
Feb 13 2018-11-11T00:
source share



All Articles