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

在绘图和尺寸、填充图例中包含NA值

  •  2
  • M.Teich  · 技术社区  · 8 年前

    我有一个数据集中的NA值,我想把它包括在我的ggplot和图例中。我认为通过指定 na.values="somecolour" 选项,如中所示 this 邮政。但是,在我的示例中,代码运行时没有绘制任何NAS,也没有在图例中包含条目。相反,缺少值的行将自动删除。下面是一些用于说明的代码:

    set.seed(42)  
    lat <- rnorm(10, 54, 12)
    long <- rnorm(10, 44, 12)
    val <- rnorm(6, 10, 3)
    val <- c(val,NA,NA,NA,NA)
    
    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),na.value = "black") +     
      guides(fill = guide_legend(), size = guide_legend()) +
      theme_minimal()
    

    我做错什么了?

    1 回复  |  直到 8 年前
        1
  •  1
  •   pogibas    8 年前

    问题来自设置 size 在里面 aes 因为你不能为 NA 中的值 scale_size_continuous .

    我的解决办法是 分别绘制NA值 (不完美,但有效)。要将它们添加到图例中,请在 俄歇电子能谱 打电话给那里的导游。

    但是,有一个问题是 钠 图例与非NA图例不匹配。为了调整对齐方式,我们必须绘制另一组不可见的 钠 最大非NA值大小的值。

    ggplot(df, aes(lat, long, size = val, fill = val)) +
        geom_point(shape = 21,alpha = 0.6) +
        geom_point(data = subset(df, is.na(val)), aes(shape = "NA"),
                   size = 1, fill = "black") +
        geom_point(data = subset(df, is.na(val)), aes(shape = "NA"),
                   size = 14, alpha = 0) +
        scale_size_continuous(range = c(2, 12), breaks = pretty_breaks(4)) +
        scale_fill_distiller(direction = -1, palette = "RdYlBu", breaks = pretty_breaks(4)) +     
        labs(shape = "         val\n",
             fill = NULL,
             size = NULL) +
        guides(fill = guide_legend(), 
               size = guide_legend(),
               shape = guide_legend(order = 1)) +
        theme_minimal() +
        theme(legend.spacing.y = unit(-0.4, "cm"))
    

    enter image description here

    PS:需要 ggplot2_3.0.0 .