konrad
konrad

Reputation: 409

How to modify the legend of a heat map generated with ggplot's geom_tile?

Is there a way to modify the legend of a heat map that was generated with geom_tile from the ggplot2 package? I would like to increase the number of tiles in the legend and to set the minimum and maximum of the shown value there.

In this example from the manual page the legend contains five colored tiles representing values from -0.4 to 0.4. How could I let e.g. 9 tile be displayed instead?

library (ggplot2)

pp <- function (n,r=4) {
   x <- seq(-r*pi, r*pi, len=n)
   df <- expand.grid(x=x, y=x)
   df$r <- sqrt(df$x^2 + df$y^2)
   df$z <- cos(df$r^2)*exp(-df$r/6)
   df
}

p <- ggplot(pp(20), aes(x=x,y=y))
p + geom_tile(aes(fill=z))

Upvotes: 2

Views: 3481

Answers (1)

smu
smu

Reputation: 9047

I guess there are several possible ways to archive this. One solution would be to specify the breaks for the legend manually.

d = pp(20)
ggplot(d, aes(x=x,y=y,fill=z)) + geom_tile() + 
    scale_fill_continuous( breaks = round( seq(-.4, .4, length.out = 10 ), 1) )

Upvotes: 4

Related Questions