合并单独的大小并在ggplot中填充图例 [英] Merge separate size and fill legends in ggplot
问题描述
我正在地图上绘制点数据,想要缩放点大小并填充到另一列.但是,ggplot为大小和填充生成两个单独的图例,而我只想要一个.我已经查看了针对同一问题的几个答案,例如这个一个,但是无法理解我在做什么错.我的理解是,如果两种美学都映射到相同的数据,那么应该只有一个图例,对吗?
I'm plotting point data on a map and would like to scale point size and fill to another column. However, ggplot produces two separate legends for size and fill, where I only want one. I have looked at several answers to the same problem, e.g. this one, but cannot understand what I'm doing wrong. My understanding ist that if both aesthetics are mapped to the same data, there should only be one legend, correct?
这里有一些代码来说明问题.任何帮助深表感谢!
Here's some code to illustrate the problem. Any help is much appreciated!
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()
推荐答案
在此答案中引用了R-Cookbook:
Looking at this answer citing 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
自变量相同.我们需要两个刻度都适合.为此,我们可以在scale_fill_distiller()
部分中再次添加breaks=pretty_breaks(4)
.然后使用guides()
我们可以实现我们想要的.
Thus we can infer that it is the same with size
and fill
arguments. We need both scales to fit. In order to do that we could add the breaks=pretty_breaks(4)
again in the scale_fill_distiller()
part. Then by using guides()
we can achieve what we want.
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()
产品:
Produces:
这篇关于合并单独的大小并在ggplot中填充图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!