Legend / scale with colour gradient start from certain value - define scale breaks

一个人想着一个人 提交于 2021-01-28 21:32:01

问题


I would like to get a customized legend for the ready heat map graph, so as it ranged from 0 to 1 with gray scale, but value before 0.01 remain white without any colour gradient on it. Managed to do it for the heat map graph but can't find any close example for the legend.

Here is my code:

> ggplot(heatmap,aes(Colour, Group, fill=p.value))+
+ scale_fill_gradientn(colours= c("white","gray","black"), values=c(0,0.011,1), breaks=c(0,0.01,0.25,0.5,0.75,1), guide=guide_colorbar(frame.colour="black"))+
+ geom_tile() + theme_bw()+ theme(legend.key.height=unit(4.5,"cm"))

and a screenshot for the heat map graph:

heatmap

Any suggestion?

Update: I was substituting the second color from "gray" to "gray95" and it looked slightly better than the graph shown. Kind of delaying the start region for the gray colour to above 0.01 (compared to the legend in the shown graph, where the gray started somewhere before 0.01). Thanks both @Nate and @tjebo for the suggestion on this! However, any helpful suggestion is still welcome.

Also, just want to clarify that I was using "white" as a representation for a specific situation, where the colour "white" was not intended to be in the range for colour gradient for the legend.


回答1:


This is a minor workaround - use "white" twice, and then start the gradient from the second position. Notice that you need to rescale the values to 0:1 first, see also ?scale_color_gradientn

library(tidyverse)
vals <- c(0, 2, 4, 10)
newvals <- scales::rescale(vals, to = 0:1)
ggplot(iris, aes(Sepal.Length, Sepal.Width, color = Petal.Length)) +
  geom_point() +
  scale_color_gradientn(colours = c("white", "white", "grey", "black"),
                        values = newvals,
                        breaks = vals, 
                        limits = c(0,10))

zoom in with black ticks. You can see the grey gradient starts immediately above 2



来源:https://stackoverflow.com/questions/65844472/legend-scale-with-colour-gradient-start-from-certain-value-define-scale-brea

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!