这个问题在这里已经有了答案:
How to combine scales for colour and size into one legend?
(2 个回答)
3年前关闭。
我正在 map 上绘制点数据,并希望缩放点大小并填充到另一列。但是,ggplot 为大小和填充生成了两个单独的图例,我只想要一个。我已经查看了同一问题的几个答案,例如this一,但无法理解我做错了什么。我的理解是,如果两种美学都映射到相同的数据,则应该只有一个图例,对吗?
下面是一些代码来说明问题。任何帮助深表感谢!
lat <- rnorm(10,54,12)
long <- rnorm(10,44,12)
val <- rnorm(10,10,3)
df <- as.data.frame(cbind(long,lat,val))
library(ggplot2)
library(scales)
ggplot() +
geom_point(data=df,
aes(x=lat,y=long,size=val,fill=val),
shape=21, alpha=0.6) +
scale_size_continuous(range = c(2, 12), breaks=pretty_breaks(4)) +
scale_fill_distiller(direction = -1, palette="RdYlBu") +
theme_minimal()
最佳答案
看着 this answer引用 R-Cookbook:
If you use both colour and shape, they both need to be given scale specifications. Otherwise there will be two two separate legends.
由此我们可以推断它与
size
相同。和 fill
论据。我们需要两个尺度都适合。为此,我们可以添加 breaks=pretty_breaks(4)
再次在scale_fill_distiller()
部分。然后通过使用 guides()
我们可以实现我们想要的。set.seed(42) # for sake of reproducibility
lat <- rnorm(10, 54, 12)
long <- rnorm(10, 44, 12)
val <- rnorm(10, 10, 3)
df <- as.data.frame(cbind(long, lat, val))
library(ggplot2)
library(scales)
ggplot() +
geom_point(data=df,
aes(x=lat, y=long, size=val, fill=val),
shape=21, alpha=0.6) +
scale_size_continuous(range = c(2, 12), breaks=pretty_breaks(4)) +
scale_fill_distiller(direction = -1, palette="RdYlBu", breaks=pretty_breaks(4)) +
guides(fill = guide_legend(), size = guide_legend()) +
theme_minimal()
生产:
关于r - 在ggplot中合并单独的大小并填充图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50862027/