In ggplot2/geom_tile, how to change fill color whice exceed the limits?
As the image, Region_4/5 are out of limis(1,11)
, so the fill color is default grey, how to change 'Region_4' to 'darkblue', 'Region_5' to 'black' . Thanks!
library(tidyverse)
library(RColorBrewer)
tile_data <- data.frame(category=letters[1:5],
region=paste0('region_',1:5),
sales=c(1,2,5,0.1,300))
tile_data %>% ggplot(aes(x=category,
y=region,
fill=sales))
geom_tile()
scale_fill_gradientn(limits=c(1,11),
colors=brewer.pal(12,'Spectral'))
theme_minimal()
CodePudding user response:
CodePudding user response:
If you want to keep the gradient scale and have two additional discrete values for off limits above and below, I think the easiest way would be to have two separate fill scales for both "in-limit" and "off-limit" values. This can be done with two separate calls to geom_tile on subsets of your data and with packages such as {ggnewscale}.
library(tidyverse)
library(RColorBrewer)
tile_data <- data.frame(category=letters[1:5],
region=paste0('region_',1:5),
sales=c(1,2,5,0.1,300))
tile_data %>% ggplot(aes(x=category,
y=region,
fill=sales))
geom_tile(data = filter(tile_data, sales < 300 | sales > 0.1 ))
scale_fill_gradientn(limits=c(1,11),
colors=brewer.pal(12,'Spectral'))
ggnewscale::new_scale_fill()
geom_tile(data = filter(tile_data, sales >= 300 | sales <= 0.1 ), mapping = aes(fill = sales<=0.1))
scale_fill_manual(NULL, values = c(`TRUE` = 'darkblue', `FALSE` = 'black'), labels = c(">=300", "<=0.1"))
theme_minimal()