代码之家  ›  专栏  ›  技术社区  ›  M.Teich

合并单独的大小并在ggplot中填充图例[复制]

  •  3
  • M.Teich  · 技术社区  · 7 年前

    我正在地图上绘制点数据,希望缩放点大小并填充到另一列。但是,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()
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   jay.sf    7 年前

    看着 this answer 引用R-Cookbook:

    如果你同时使用颜色和形状,它们都需要给出比例规格。否则将有两个独立的图例。

    因此我们可以推断它与 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

    推荐文章