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

查看:735
本文介绍了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?

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

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:

require(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)
  df
}

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

但是当我将休息更改为

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

推荐答案

这是非常重要的在ggplot中, break 基本上不会改变比例本身。

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天全站免登陆