R ggplot2 -- Set z axis limit in stat_contour plot

2.5k views Asked by At

In ggplot2 x and y axis limits can be specified using a shorthand approach (xlim(0, 1)) or a more structured approach (scale_x_continuous(limits = c(0, 1))). How do I do this for the z axis in a contour plot?

Reproducible example:

library(ggplot2)
library(akima)

x <- runif(40)
y <- runif(40)
z <- runif(40, min = 0.5, max = 1)
fld <- interp(x = x,
              y = y,
              z = z,
              xo = seq(min(x), max(x), length = 40),
              duplicate = 'mean')
gdat <- interp2xyz(fld, data.frame = TRUE)

ggplot(gdat, aes(x = x, y = y, z = z)) +
  geom_tile(aes(fill = z)) +
  stat_contour(aes(fill = ..level..), geom = 'polygon', binwidth = 0.005) +
  geom_contour(colour = 'white', alpha = 0.5) +
  scale_fill_gradient(low = 'white', high = 'red') +
  theme_bw()

ggplot2 stat_contour plot

In this example, I artificially constrained the z axis to range from 0.5 to 1. However, I would like to plot it so that the white colour gradient begins at 0 instead of 0.5. Any suggestions on how to do this?

0

There are 0 answers