将NA值添加到ggplot图例以获取连续数据图

Hil*_*ary 9 r legend ggplot2 na

我正在使用ggplot将数据值映射到(强化的)SpatialPolygonsDataFrame,但是许多多边形都有NA值,因为没有可用的数据.

我使用na.value ="white"来正确显示缺失的数据,但我想在图例中添加带有白色填充的框(或单独的图例),标签为"无数据".

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 (%)")
Run Code Online (Sandbox Code Playgroud)

(我有一个很好的图像来说明这一点,但没有足够的声誉点来发布它)

我已经读过这篇文章了,但是我的数据是连续的(不是离散的),而且这个,但是我无法弄清楚如何将'line'变化调整为'fill'.

谢谢您的帮助!!

R V*_*Vij -1

您可以使用 0 替换您的 NA

data[is.na(data)] <- 0
Run Code Online (Sandbox Code Playgroud)

这样你的 nas 将被零替换,并且你的图例将显示“0s”

为了向我们展示图像,您可以拥有一个博客并可以将链接粘贴到此处

  • 这不涉及OP描述的情况,其中“没有数据”与“在地图上为该区域收集数据但有0个案例”不同 - 这应该不是ggplot2的功能请求是否可以选择显示 NA、选择如何标记它们、为它们着色并将它们包含在图例中? (2认同)