简体   繁体   English

ggplot标度颜色渐变到数据范围之外的范围

[英]ggplot scale color gradient to range outside of data range

I am looking for a way to stretch a color gradient between two values and label the legend, regardless of the range of data values in the dataset. 我正在寻找一种方法来扩展两个值之间的颜色渐变并标记图例,而不管数据集中数据值的范围如何。 Essentially, is there a functional equivalent to ylim() for color gradients? 本质上,是否存在与ylim()等效的颜色渐变功能?

Given code which plots az value typically between -1 and 1, I can plot and label a gradient if the breaks are within the data range: 给定的代码通常会在-1和1之间绘制z值,如果中断在数据范围内,我可以绘制并标记渐变:

library(ggplot2)

#generator from http://docs.ggplot2.org/current/geom_tile.html
pp <- function (n, r = 4) { 
  x <- seq(-r * pi, r * pi, len = n)
  df <- expand.grid(x = x, y = x)
  df$r <- sqrt(df$x^2 + df$y^2)
  df$z <- cos(df$r^2) * exp(-df$r / 6)
  return(df)
}

t <- pp(30)
summary(t)
b <- c(-.5, 0, .5)
colors <- c('navyblue', 'darkmagenta', 'darkorange1')
p <- ggplot(data = t, aes(x = x, y = y))+
  geom_tile(aes(fill = z))+
  scale_fill_gradientn(colors = colors, breaks = b, labels = format(b))
ggsave(plot = p, filename = <somefile.png>, height = 3, width = 4)

格雷厄姆·杰弗里斯ggplot比例填充示例

But when I change the breaks to values outside of the observed range, the gradient coloring doesn't seem to adjust and the gradient labels don't appear. 但是,当我将中断更改为超出观察范围的值时,渐变颜色似乎无法调整,并且渐变标签也不会出现。

b <- c(-3, 0, 3)

格雷厄姆·杰弗里斯ggplot比例尺填充示例2

It's very important to remember that in ggplot, breaks will basically never change the scale itself. 重要的是要记住,在ggplot中, breaks基本上不会改变刻度本身。 It will only change what is displayed in the guide or legend. 它只会更改指南或图例中显示的内容。

You should be changing the scale's limits instead: 您应该改为更改秤的限制:

ggplot(data=t, aes(x=x, y=y)) +
  geom_tile(aes(fill=z)) +
  scale_fill_gradientn(limits = c(-3,3),
  colours=c("navyblue", "darkmagenta", "darkorange1"),
  breaks=b, labels=format(b))

And now if you want the breaks that appear in the legend to extend further, you can change them to set where the tick marks appear. 现在,如果您希望图例中出现的间断进一步扩展,可以更改它们以设置刻度线出现的位置。

A good analogy to keep in mind is always the regular x and y axes. 要牢记的一个很好的类比始终是规则的x和y轴。 Setting "breaks" there will just change where the tick marks appear. 设置“中断”将仅更改刻度线出现的位置。 If you want to alter the extent of the x or y axes, you'd typically change a setting like their "limits". 如果你想改变x或y轴的程度 ,你通常会改变他们一样的“极限”的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM