Add NA value to ggplot legend for continuous data

2019-04-05 18:25发布

问题:

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.value = "white" to display the missing data correctly, but I'd like to add a box with a white fill in the legend (or a separate legend) with the label "no data".

library(ggplot2)

india.df <- read.csv('india.df.csv') 
# (I don't know how to provide this file to make the code reproducible)

ggplot() +
geom_polygon(data=india.df, aes(x = long, y = lat, group = group, fill=Area_pct)) +
scale_fill_gradient(low="orange2", high="darkblue", na.value = "white") +
geom_path(data=india.df, aes_string(x = x, y = y, group = group), color = "gray", size = 0.25) +
theme_bw() +
coord_map() +
labs(title = "Rice Under Irrigation in Gujarat - 2001", 
     fill = "Area (%)")

(I have a great image to illustrate this but don't have enough reputation points to post it)

I've read this, but my data is continuous (not discrete), and this, but I can't figure out how to adapt the 'line' change to 'fill'.

Thanks for the help!!

回答1:

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



回答2:

Try this:

ggplot(all your info) + geom_point(na.rm = TRUE) + geom_line(na.rm = TRUE)