我正在使用 R 中的 usmaps() 包来创建美国地图。我的数据设置如下:
Ces_State_Only:
状态 | 1990 |
---|---|
阿拉巴马州 | 0.2 |
阿拉斯加 | 0.31 |
亚利桑那州 | 0.40 |
我想创建一个叶绿素图。我想将我的数据分为以下几类:0-0.2、0.2-0.25、0.25-0.3、0.3-0.33、0.33-36、>36。
我的代码是:
plot_usmap(data = Ces_State_only, values = "1990") + scale_colour_gradientn(colours = "Blues", breaks = c(0,.2, .25, 0.3, 0.33, 0.36, 1),limits = c(0, 100))
此代码有效,但它不会存储我的数据。
我还尝试在映射数据之前对数据进行分箱:
Ces_State_only$Ninety_bin <- cut(Ces_State_only$`1990`,breaks = c(0,0.2, 0.25, 0.3, 0.33, 0.36,1))
plot_usmap(data = Ces_State_only, values = "Ninety_bin") + scale_fill_brewer(palette="Blues",
aesthetics = "fill",
na.value = "grey50")+ theme(legend.position = "right")
但是,这只会在美国地图上创建三种不同的颜色(对于以下容器:0-0.2、0.2-0.25 和 0.25-0.3)。
有什么建议或想法吗?
提前谢谢您!
更新 从
ggplot2 >= 3.5.0
开始,还必须将 show.legend=TRUE
添加到 plot_usmap()
以显示未使用因子级别的图例键:
library(usmap)
library(ggplot2)
plot_usmap(
data = Ces_State_only, values = "Ninety_bin",
show.legend = TRUE
) +
scale_fill_brewer(
palette = "Blues",
aesthetics = "fill",
na.value = "grey50",
drop = FALSE
) +
theme(legend.position = "right")
原答案
问题是默认情况下使用的因子水平会下降。您可以通过在
drop=FALSE
中设置 scale_fill_brewer
来防止这种情况:
library(usmap)
library(ggplot2)
plot_usmap(data = Ces_State_only, values = "Ninety_bin") +
scale_fill_brewer(
palette = "Blues",
aesthetics = "fill",
na.value = "grey50",
drop = FALSE
) +
theme(legend.position = "right")
数据
Ces_State_only <- data.frame(
check.names = FALSE,
state = c("Alabama", "Alaska", "Arizona"),
`1990` = c(0.2, 0.31, 0.4)
)
Ces_State_only$Ninety_bin <- cut(
Ces_State_only$`1990`,
breaks = c(0, 0.2, 0.25, 0.3, 0.33, 0.36, 1)
)