2

I plot heatmaps using the levelplot function from the lattice package. The values in my matrix range from -1 to 1 and I used the following scale:

cols <- colorRampPalette(c("blue", "white", "red"))(256)

A small example:

d <- 20
df <- expand.grid(x = 1:d, y = 1:d)
df$z <- runif(d*d, -1, 1)

levelplot(z ~ x * y, data = df,
          col.regions = cols)

enter image description here

I wish to adjust the scale so that a bigger proportion of the scale is white. I assume I have to manually define where the transition starts or better yet define different "transition speeds" - a slower one when I´m closer to 0 (i.e. white), and a quicker one when I get closer to 1 or -1.

Any advice for how to do this would be greatly appreciated!

Henrik
  • 65,555
  • 14
  • 143
  • 159
oak
  • 21
  • 1
  • I you're not restricted to use `lattice`, here's how you may do it in `ggplot`: [Is it possible to define the “mid” range in scale_fill_gradient2()?](http://stackoverflow.com/questions/21758175/is-it-possible-to-define-the-mid-range-in-scale-fill-gradient2/21758729#21758729) – Henrik May 14 '17 at 10:31
  • Thanks for the link! If possible I would like to stick to lattice because I´d like to plot a pre-existing matrix rather than calculate a correlation matrix and I´ve found this to be easier in lattice... – oak May 14 '17 at 14:32
  • OK! But I can assure you, the transistion from `lattice` to `ggplot` is not that difficult. Good luck anyway! – Henrik May 15 '17 at 14:12

1 Answers1

0

You could switch the interpolation to spline for a smoother transition.

cols <- colorRampPalette(c("blue", "white", "red"), interpolate = "spline")(256)

enter image description here

You could also go with the much nicer palettes from RColorBrewer

cols2 <- colorRampPalette(RColorBrewer::brewer.pal(11, "RdBu"))(256)
levelplot(z ~ x * y, data = df, col.regions = rev(cols2))

enter image description here

Johan Larsson
  • 3,496
  • 18
  • 34