4

Here is starting example I'm trying to modify:

library(reshape2)

data <- mtcars[, c(1,3,4,5,6,7)]
cormat <- round(cor(data),2)
melted_cormat <- melt(cormat, na.rm = TRUE)

ggplot(
  data = melted_cormat,
  aes(Var1, Var2, fill=value)
) +
  geom_tile() +
  geom_text(
    aes(Var2, Var1, label = value)
  ) +
  scale_fill_gradient2(
    low = 'red',
    high = 'blue',
    mid = 'white', 
    midpoint = 0, # <-- look at this
    limit = c(-1, 1)
  ) 

This code creates a plot:

enter image description here

But when I change the only midpoint to midpoint = -0.5 plot looks like:

enter image description here

In my opinion, the output is not correct since I clearly stated low = 'red' and in the plot the lowest value color is between red and white.

I'm looking for a solution how to maintain midpoint = -0.5 and a full gradient from -1 (red) to -0.5 (white).

Everettss
  • 15,475
  • 9
  • 72
  • 98

1 Answers1

9

The solution is described here:

library(reshape2)
library(scales)
data <- mtcars[, c(1,3,4,5,6,7)]
cormat <- round(cor(data),2)
melted_cormat <- melt(cormat, na.rm = TRUE)

ggplot(
  data = melted_cormat,
  aes(Var1, Var2, fill=value)
) +
  geom_tile() +
  geom_text(
    aes(Var2, Var1, label = value)
  ) +
  scale_fill_gradientn(
   colors=c("red","white","blue"),
   values=rescale(c(-1,-0.5,1)),
   limits=c(-1,1)
  )

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • Great! Now I know that this is possible with `scale_fill_gradientn` but I'm still investigating why `high` and `low` are so confusing when `midpoint` is asymmetric in `scale_fill_gradient2`. – Everettss Mar 03 '18 at 10:58
  • @Everettss OK. I understand. The `scale_fill_gradient2` function uses the rescaler `rescale_mid` of the `scales` package. I think it could be interesting to understand how it works trying: `rescale_mid(seq(-1,1,length.out=11),c(0,1),c(-1,1),0)` and `rescale_mid(seq(-1,1,length.out=11),c(0,1),c(-1,1),-0.5)`. See also: `scales:::rescale_mid.numeric` – Marco Sandri Mar 03 '18 at 11:35