Ruari Rhodes
Ruari Rhodes

Reputation: 59

Creating semi-discrete colourbar in ggplot

I'm attempting to create a plot using geom_tile. The source data is continuous, but I want to colour it using discrete levels to make the resulting plot easier to read. I want the resulting colour bar to show the discrete levels, but to refer to the underlying data as continuous. Something like this: colourbar

which is essentially a continuous colour scale overlaid with discrete values.

So far I have this:

require( ggplot2)

x <- rep( 1:10, 10)
y <- rep( 1:10, each=10)
z <- rnorm( length(y))

df <- data.frame( x, y, z)

ggplot( df) + geom_tile( aes( x, y, fill=z)) +
scale_fill_gradient2( low="blue", mid="white", high="red", midpoint=0)

Giving this: continuous scale

I want to bin the continuous variable "z" to set levels, so I can use cut:

df$discrete_z <- cut( z, breaks=seq( -3,3, 1), include.lowest=T)

ggplot( df) + geom_tile( aes( x, y, fill=discrete_z)) +   
scale_fill_brewer( type="div", palette="PRGn", guide="legend")

Giving this: discrete scale

Which is a lot closer, but now the numbers are represented as a range on each colour "block", whereas I am trying to get the numbers to lie individually between the colour blocks to give a better impression of a continuous scale.

Upvotes: 2

Views: 183

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23129

If you choose the lower bounds of each intervals to be the bin name, you get something like the following:

df$discrete_z <- cut( z, breaks=seq( -3,3, 1), labels = seq( -3,2, 1), include.lowest=T)

ggplot( df) + geom_tile( aes( x, y, fill=discrete_z)) +   
  scale_fill_brewer( type="div", palette="PRGn", guide="legend")

enter image description here

Upvotes: 2

Related Questions