简体   繁体   English

结合连续填充(颜色)和alpha刻度的指南

[英]Combine guides for continuous fill (color) and alpha scales

In ggplot2, I am making a geom_tile plot where both color and alpha vary with the same variable, I would like to make a single guide that shows the colors the way they appear on the plot instead of two separate guides. 在ggplot2中,我正在制作一个geom_tile图,其中颜色和alpha都随同一个变量而变化,我想制作一个单一的指南,显示颜色与它们在图上的显示方式,而不是两个单独的指南。

library(ggplot2)

x <- seq(-10,10,0.1)
data <- expand.grid(x=x,y=x)
data$z <- with(data,y^2 * dnorm(sqrt(x^2 + y^2), 0, 3))
p <- ggplot(data) + geom_tile(aes(x=x,y=y, fill = z, alpha = z))
p <- p + scale_fill_continuous(low="blue", high="red") + scale_alpha_continuous(range=c(0.2,1.0))
plot(p)

This produces a figure with two guides: one for color and one for alpha. 这会产生一个带有两个指南的图形:一个用于颜色,一个用于alpha。 I would like to have just one guide on which both color and alpha vary together the way they do in the figure (so as the color shifts to blue, it fades out) 我想只有一个指南,颜色和alpha在图中的方式一致变化(因此颜色变为蓝色,淡出)

For this figure, I could achieve a similar effect by varying the saturation instead of alpha, but the real project in which I am using this, I will be overlaying this layer on top of a map, and want to vary alpha so the map is more clearly visible for smaller values of the z-variable. 对于这个图,我可以通过改变饱和度而不是alpha来实现类似的效果,但是我正在使用它的真实项目,我将覆盖这个图层在地图上,并且想要改变alpha,所以地图是对于较小的z变量值,可以更清楚地看到。

I don't think you can combine continuous scales into one legend, but you can combine discrete scales. 我不认为您可以将连续比例​​组合成一个图例,但您可以组合离散比例。 For example: 例如:

# Create discrete version of z
data$z.cut = cut(data$z, seq(min(data$z), max(data$z), length.out=10))

ggplot(data) +  
  geom_tile(aes(x=x, y=y, fill=z.cut, alpha=z.cut)) +
  scale_fill_hue(h=c(-60, -120), c=100, l=50) +
  scale_alpha_discrete(range=c(0.2,1))

You can of course cut z at different, perhaps more convenient, values and change scale_fill_hue to whatever color scale you prefer. 您当然可以在不同的,可能更方便的值上剪切z ,并将scale_fill_hue更改为您喜欢的任何颜色范围。

在此输入图像描述

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

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