Home > Blockchain >  Reverse legend in geom_contour
Reverse legend in geom_contour

Time:05-15

I'm struggling to find the right solution to reverse the legend, so that red is at the bottom and greens at the top. Here's a simple example.

library(ggplot2)
library(dplyr)

x = seq(0.01,1,0.01)
y = seq(0.01,1,0.01)
df <- expand.grid(x = x, y = y)
df <- df %>% mutate(z = x*y/(1   x))

ggplot(df, aes(x = x, y = y, z = z))  
  geom_contour_filled(bins = 10)  
  geom_contour(bins = 20, colour = "grey")  
  scale_fill_manual(values = rainbow(20)) 

CodePudding user response:

Couple of issues:

  1. You're using 20 colours to describe 10 bins.
  2. You're using the entire rainbow for a red-green gradient.

Suggested fix is to use the end and rev arguments of the rainbow() function.

library(ggplot2)
library(dplyr)

x = seq(0.01,1,0.01)
y = seq(0.01,1,0.01)
df <- expand.grid(x = x, y = y)
df <- df %>% mutate(z = x*y/(1   x))

ggplot(df, aes(x = x, y = y, z = z))  
  geom_contour_filled(bins = 10)  
  geom_contour(bins = 20, colour = "grey")  
  scale_fill_manual(values = rainbow(10, end = 0.4, rev = TRUE)) 

Created on 2022-05-15 by the reprex package (v2.0.1)

Aside from that, you might want to consider to take a palette that has better visual properties than a rainbow. For example, can you really discriminate the 2nd-4th green bins visually? A close palette with better (but not perfect) properties is viridisLite::turbo(10, begin = 0.5).

  • Related