r - 保留图例中 ggplot 中地图的所有中断
问题描述
我正在使用地图,并且我正在努力将所有用于休息的钥匙都保留在传说中,即使没有任何案例落在这些休息时间。
我正在使用其他问题的一些代码,经过编辑以显示我的问题。老问题在这里:R Custom Color Scale for Plotting
在此示例中,没有州|县落入“1001 - 10000”区间,但我需要将该键保留在图例中。代码如下:
stateNames <- c("alabama", "alabama", "arizona", "arkansas", "california",
"colorado", "connecticut", "florida", "georgia")
countyNames <- c("autauga", "blount", "apache", "bradley", "orange",
"boulder", "new haven", "flagler", "turner")
dataCol <- c(0, 5, 15, 50, 150, 1000, 500, 249, 30)
map.county <- map_data('county')
counties <- unique(map.county[,5:6])
data_map <- merge(counties, data.frame(region=stateNames,
subregion=countyNames,
data1= dataCol),
by=c("region","subregion"), all.x=T, all.y=F
)
data_map$data1[which(is.na(data_map$data1))] <- 0
map.county <- data.table(map_data('county'))
setkey(map.county,region,subregion)
data_map <- data.table(data_map)
setkey(data_map,region,subregion)
map.df <- map.county[data_map]
map.df$brks <- cut(map.df$data1,
breaks = c(0, 1, 10, 25, 100, 250, 1000, 10000),
labels = c("0", "1 - 10", "11 - 25", "26 - 100",
"101 - 250", "251 - 1000", "1001 - 10000"),
include.lowest = TRUE)
ggplot(map.df, aes(x=long, y=lat, group=group, fill=brks)) +
geom_polygon(colour = "grey", size = 0.001) +
coord_map() +
expand_limits(x = map.county$long, y = map.county$lat) +
scale_fill_brewer(palette = "YlOrRd") +
theme_void() +
theme(legend.position = "right")
解决方案
您可以简单地将参数添加drop = FALSE
到scale_fill_brewer
:
ggplot(map.df, aes(x=long, y=lat, group=group, fill=brks)) +
geom_polygon(colour = "grey", size = 0.1) +
coord_map() +
expand_limits(x = map.county$long, y = map.county$lat) +
scale_fill_brewer(palette = "YlOrRd", drop = FALSE) +
theme_void() +
theme(legend.position = "right")
它回答了你的问题吗?
推荐阅读
- javascript - 尝试通过使用 chrome-webrequest API 重写 http-request-header 来更改 chrome-browser 的 UserAgent,但效果不佳
- mongodb - 更新路径“packages.$[pkg10].items”会在“packages”处产生冲突
- c# - 如何使用 Entity Framework Core 检索外键
- python - EnvironmentError:没有名为“fastcpp”的工具:不是 Zip 文件:
- excel - Excel中两个时间戳之间的分钟差
- java - authorize.net 或 useepay 中是否有用于以下目的的功能?
- perl - 如果 Perl 的这两种写作风格有什么区别,为什么结果不同?
- ios - 如何在表格视图中拉动刷新时修复冻结的活动指示器
- azure - Azure 默认阅读器与内置监控阅读器
- python - 在 python 中使用 plotly 绘制具有百分比差异的漏斗图