ggplot 将颜色渐变缩放到数据范围之外 [英] ggplot scale color gradient to range outside of data range

查看:41
本文介绍了ggplot 将颜色渐变缩放到数据范围之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来拉伸两个值之间的颜色渐变并标记图例,而不管数据集中的数据值范围如何.本质上,是否有与 ylim() 等效的颜色渐变功能?

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?

给定通常在 -1 和 1 之间绘制 z 值的代码,如果中断在数据范围内,我可以绘制和标记梯度:

Given code which plots a z value typically between -1 and 1, I can plot and label a gradient if the breaks are within the data range:

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)

但是当我将中断更改为观察范围之外的值时,渐变着色似乎没有调整,渐变标签也没有出现.

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 中,breaks 基本上不会改变比例本身.它只会更改指南或图例中显示的内容.

It's very important to remember that in ggplot, breaks will basically never change the scale itself. 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.

要记住的一个很好的类比是常规的 x 轴和 y 轴.在那里设置中断"只会改变刻度线出现的位置.如果您想更改 x 或 y 轴的范围,您通常会更改诸如限制"之类的设置.

A good analogy to keep in mind is always the regular x and y axes. 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".

这篇关于ggplot 将颜色渐变缩放到数据范围之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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