r - 在ggplot中合并单独的大小并填充图例

标签 r ggplot2 gis ggmap

这个问题在这里已经有了答案:





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()

生产:
enter image description here

关于r - 在ggplot中合并单独的大小并填充图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50862027/

相关文章:

r - 通过R中的相同函数修改数据集的多列

r - R中ggplotly中图例的奇怪格式

r - 使用 ggplot2 绘制混合效应模型

javascript - 给定经纬对列表,在传单中查找中心和缩放级别

r - 根据观察复制和修改数据帧的行 [R]

r - 根据前一行中的值填充缺失的列值

r - 在 R 中绘制 2D 表格对象时控制轴标签的格式/位置

openlayers - 如何将 OpenLayers 3 与 Proj4js 一起使用

gps - 减少GPS轨迹数据丢弃冗余数据的算法?

r - 将 Rle 对象的 S4 DataFrame 转换为 R 中的稀疏矩阵