Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asymmetric midpoint in scale_fill_gradient2 results with trimmed color on the shorter edge

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).

like image 547
Everettss Avatar asked Oct 18 '25 17:10

Everettss


1 Answers

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

like image 63
Marco Sandri Avatar answered Oct 21 '25 09:10

Marco Sandri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!