ggplot2正负值不同的颜色渐变 [英] ggplot2 positive and negative values different color gradient

查看:789
本文介绍了ggplot2正负值不同的颜色渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用R(3.0.1)和ggplot2(0.9.3.1)。我有包含正值和负值的数据,并且我想获得一个geom_tile图,其中正数和负数存在不同的颜色比例梯度(例如,正数从红到黄,负数从蓝到负青色)。我能够使用scale_fill_gradientn(请参见下文)来达到我想要的效果,但这会导致在中点(0)处包含白色颜色的一个连续渐变。我需要避免这些中点颜色,因此不知何故需要将渐变打破为零。换句话说,我需要两个连续的梯度(一个用于正值,一个用于负值),它们在零处有一个不连续的中断。任何帮助?
$ b $ pre $ lt; code> dat< - data.frame(Row = rep(x = LETTERS [1:5],times =
,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(colors = c (c(-1,0,1)))

解决方案

使青色和黄色之间的距离非常小:

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


该指南没有物理中断,但颜色映射像你一样抄写。

I am using R (3.0.1), and ggplot2 (0.9.3.1). I have data that contains both positive and negative values, and I want to obtain a geom_tile plot in which there are different color scale gradients for the positive and the negative numbers (e.g., positive numbers go from red to yellow, negative numbers from blue to cyan). I am able to approach what I want using scale_fill_gradientn (see below), but this results in one continuous gradient that includes "white" color at the midpoint (0). I need to avoid these midpoint colors, and therefore somehow need to "break" the gradients at zero. In other words, I need two continuous gradients (one for positive values, one for negative values) that have a discrete break at zero. Any help?

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)))

解决方案

Make the range between the cyan and yellow very very small:

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)))

The guide does not have a physical break in it, but the colors map as you described.

这篇关于ggplot2正负值不同的颜色渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆