以下是美国在r:
中陈述来自state.x77数据集的示例数据mydf = structure(list(usa_state = structure(1:5, .Label = c("Alabama",
"Alaska", "Arizona", "Arkansas", "California"), class = "factor"),
Life.Exp = c(69.05, 69.31, 70.55, 70.66, 71.71), HS.Grad = c(41.3,
66.7, 58.1, 39.9, 62.6)), .Names = c("usa_state", "Life.Exp",
"HS.Grad"), class = "data.frame", row.names = c(NA, -5L))
> mydf
usa_state Life.Exp HS.Grad
1 Alabama 69.05 41.3
2 Alaska 69.31 66.7
3 Arizona 70.55 58.1
4 Arkansas 70.66 39.9
5 California 71.71 62.6
>
我想在美国州地图上绘制它。我可以使用以下代码绘制地图:
all_states <- map_data("state")
ggplot() + geom_polygon( data=all_states, aes(x=long, y=lat, group = group),colour="gray", fill="white" )
但我无法在地图上绘制条形图。谢谢你的帮助。
答案 0 :(得分:1)
我借鉴了两个很好的资料来回答这个问题:
<强>解强>
mydf <- structure(list(usa_state =
structure(1:5,
.Label = c("Alabama", "Alaska", "Arizona", "Arkansas", "California"), class = "factor"),
Life.Exp = c(69.05, 69.31, 70.55, 70.66, 71.71),
HS.Grad = c(41.3, 66.7, 58.1, 39.9, 62.6)),
.Names = c("usa_state", "Life.Exp", "HS.Grad"),
class = "data.frame", row.names = c(NA, -5L))
library(ggplot2)
library(maps)
library(RColorBrewer) # lots of color palettes for these kind of charts
library(data.table) # for sorting by key
library(mapproj) #coord_maps() needed this
all_states <- map_data("state")
# You need to merge dataset with maps one with long and lat.
# But you need same key so lets change state to region used in maps all_states
# Note I lowercased it to get the match
mydf$region <- tolower(mydf$usa_state)
totaldf <- merge(all_states, mydf, by = "region")
# switched to data.table to fix the cut up map issue
# getting sort by region then order
totaldt <- as.data.table(totaldf)
setkey(totaldt, region, order)
ggplot(data = totaldt,
aes(x = long, y = lat, group = group, fill = HS.Grad)) +
geom_polygon() + coord_map() +
scale_fill_gradientn("", colours=brewer.pal(9, "GnBu"))
不要忘记给我打分
如果您的数据没有按地区排序,然后按顺序排序,那么您将获得这样的补丁地图。
我使用data.table
包并键入数据。如果您需要合并大量数据,data.table也会快得多。您使用格式X [Y]。如果您不熟悉此软件包,请参阅data.table cheatsheet。
最终地图
这适用于您示例中的HS.Grid
。通过更改fill = myvariable
请注意,并未显示所有状态,因为测试数据仅限于这些状态。在更完整的例子中,您将看到更多的状态。
你也会看到阿拉斯加失踪。它不在地图中 - 请参阅@jazzurro中的this answer,了解使用setdiff对州名进行的实际测试。