Dahaniel
Dahaniel

Reputation: 403

How can I create a colormap with a fixed color for 0 in R / ggplot

I am producing heatmaps of measurement using ggplot2. The data contains positive and negative values and I use the rainbow() palette for coloring.

I have different data sets and would like to scale the colora in a way that the minimum, maximum and 0 values of each data set get the same colors assigned. I could only find out to set the minimum and maximum using limits=...

How can I also define a given color for 0?

Here is my minimal example, if I would for example use rainbow(5), I would like the 3rd color to be the zero color.

data <- read.csv("http://protzkeule.de/data.csv")
ggplot(data=data, aes(x=variable, y=meas)) + 
  geom_tile(aes(fill=value)) + 
  scale_fill_gradientn(colours=rev(rainbow(255)),limits=c(-.2,.4))

Upvotes: 1

Views: 1653

Answers (1)

Benvorth
Benvorth

Reputation: 7722

Perhaps a different approach: For my plots I found it easier to cut the values used for the Colors:

ggplot(...) +
stat_bin2d (aes(fill=ifelse(..count..>20,20,..count..)), bins = 10) +
scale_fill_gradientn("Count", colours=c("blue", "yellow", "red")) + ...

Upvotes: 1

Related Questions