r - ggplot2正负值不同颜色渐变

标签 r ggplot2

我正在使用 R (3.0.1) 和 ggplot2 (0.9.3.1)。我有包含正值和负值的数据,我想获得一个 geom_tile 图,其中正数和负数有不同的色阶渐变(例如,正数从红色变为黄色,负数从蓝色变为青色)。我可以使用 scale_fill_gradientn(见下文)来达到我想要的效果,但这会导致一个连续渐变,在中点 (0) 处包含“白色”颜色。我需要避免这些中点颜色,因此需要以某种方式将渐变“打破”为零。换句话说,我需要两个连续梯度(一个用于正值,一个用于负值)在零处具有离散中断。有什么帮助吗?

dat <- data.frame(Row = rep(x = LETTERS[1:5], times = 10)
 , Col = rep(x = LETTERS[1:10], each = 5)
 , Y = runif(n = 50, min = -1, max = 1))

p <- ggplot(data =  dat, aes(x = Row, y = Col)) + 
  geom_tile(aes(fill = Y)) +
  scale_fill_gradientn(colours=c("blue","cyan","white", "yellow","red"), values=rescale(c(-1,0,1)))

最佳答案

使青色和黄色之间的范围非常小:

ggplot(data =  dat, aes(x = Row, y = Col)) + 
  geom_tile(aes(fill = Y)) +
  scale_fill_gradientn(colours=c("blue","cyan","white", "yellow","red"), 
    values=rescale(c(-1,0-.Machine$double.eps,0,0+.Machine$double.eps,1)))

enter image description here

该指南中没有物理中断,但颜色映射如您所描述。

关于r - ggplot2正负值不同颜色渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700938/

相关文章:

r - 让 transition_states、geom_label_repel 和 enter_fade 协同工作

r - 从 sendCustomMessage() 在 htmlwidgets/plotly 对象中定义悬停信息

windows - 无法将 unicode .csv 读入 R

r - 如何更改 r shinydashboard 中数据表中列的对齐方式?

r - 将双变量绘制为 R 中的多个因子

r - 如何绘制带有躲避位置的图形?

r - 将R中的两列求和

r - 以概率选择特定数字

r - 如何对齐多行标题

r - 叠加密度图,ggplot2,R 3.5.1。 , 错误 : Aesthetics must be either length 1 or the same as the data