Add NA value to ggplot legend for continuous data map

后端 未结 3 591
走了就别回头了
走了就别回头了 2021-02-06 00:51

I\'m using ggplot to map data values to a (fortified) SpatialPolygonsDataFrame, but many of the polygons have NA values because there is no data available.

I used na.va

相关标签:
3条回答
  • 2021-02-06 01:12

    you can replace your NAs with 0 using

    data[is.na(data)] <- 0
    

    that way your nas will be replaced by zero and yout legend will show "0s"

    And to show us the image you can have a blog and can paste the link here

    0 讨论(0)
  • 2021-02-06 01:20

    Try this:

    ggplot(all your info) + geom_point(na.rm = TRUE) + geom_line(na.rm = TRUE)
    
    0 讨论(0)
  • 2021-02-06 01:24

    You could make use of the behavior of ggplot which creates a legend when specifying certain aesthetics within aes()
    I am creating some dummy data and am using geom_map instead of geom_polygon, which I find easier. You can then use override.aes to specify the fill of the legend key with the NA value. You can then easily rename the legend etc.

    library(tidyverse)
    
    worldData <- map_data('world') %>% fortify()
    india.df <- data.frame(region = 'India', Area_pct = 2, stringsAsFactors = FALSE) %>% right_join(worldData, by = 'region')
    
    na.value.forplot <- 'white'
    
    ggplot() +
      geom_map(data = india.df, map = india.df, aes(x = long, y = lat, fill = Area_pct, map_id = region, color = 'NA')) +
      scale_fill_gradient(low="orange2", high="darkblue", na.value = na.value.forplot) +
      scale_color_manual(values = 'black', labels = 'Missing value') +
      guides(color = guide_legend(override.aes = list(fill = na.value.forplot)))
    #> Warning: Ignoring unknown aesthetics: x, y
    

    Created on 2019-07-18 by the reprex package (v0.3.0)

    0 讨论(0)
提交回复
热议问题