I have a data frame, df:
df <- structure(list(animal = c("cat", "cat", "cat", "cat", "cat",
"cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat", "cat",
"cat", "cat", "cat", "cat"), id = c("201", "202", "203", "204",
"215", "217", "201", "202", "203", "204", "215", "217", "201",
"202", "203", "204", "215", "217"), tissue = c("tail", "tail",
"tail", "tail", "tail", "tail", "whiskers", "whiskers", "whiskers",
"whiskers", "whiskers", "whiskers", "feet", "feet", "feet", "feet",
"feet", "feet"), value = c(0.5, 2.2, 0, 0.2, 0, 0, 2.8, 19.9,
0, 85, 0, 0, 1.9, 4.1, 0, 0.4, 0, 120)), row.names = c(NA, -18L
), class = "data.frame")
head(df)
animal id tissue value
1 cat 201 tail 0.5
2 cat 202 tail 2.2
3 cat 203 tail 0.0
4 cat 204 tail 0.2
5 cat 215 tail 0.0
6 cat 217 tail 0.0
I have the following plotting function:
p <- ggplot(df, aes_string(x = "id", y = "tissue", fill = "value"))
geom_tile(color = "white")
geom_text(aes_string(label = "value"), color = "black", size = 2)
scale_fill_gradient(
low = "white", high = "red", na.value = "#D0D0D0")
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
This produces:
I would like the zero values to be plotted in white, but any value above zero to start from an off-red (eg. #FEECE3).
I have tried this:
p <- ggplot(df, aes_string(x = "id", y = "tissue", fill = "value"))
geom_tile(color = "white")
geom_text(aes_string(label = "value"), color = "black", size = 2)
scale_fill_gradient2(
low = "white", mid = "#FEECE3", high = "red", na.value = "#D0D0D0",
midpoint = 1)
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
But it plots the zeros in the off-red colour.
How can I get just the zeros to plot in white?
CodePudding user response:
You could use scale_fill_gradientn
. Set your three colours to white, off-white and red, and set the values at which they reach these colors as 0, the smallest possible non-zero number, and 1.
ggplot(df, aes_string(x = "id", y = "tissue", fill = "value"))
geom_tile(color = "white")
geom_text(aes_string(label = "value"), color = "black", size = 2)
scale_fill_gradientn(colours = c('white', "#FEECE3", 'red'),
values = c(0, .Machine$double.eps, 1))
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))