我想在R中创建美国地图,并根据度量以热图类型的方式对州进行颜色编码。我知道如何使用googleVis api来执行此操作,但是我无法使用代码,并且没有过渡也不是那么好。完成这项工作的最快方法是什么?我对地图包很熟悉,但是我无法获得合作的颜色。我相信这被称为choropleth地图。
ggplot2软件包中有完整的示例,请参见?map_data
。
library(ggplot2)
example(map_data)
(希望答案可能仍然对某人有用)
RevolutionAnalytics使用example功能具有出色的地图可视化spplot()
。这是那里的图片:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9QWmw1ai5wbmcifQ==” alt =“在此处输入图像描述”>
在UScensus2000tract软件包中有一个以人口为导向的螺旋形的例子。
# Transform dataset to correct format
crimes <- data.frame(state = tolower(row.names(USArrests)), USArrests)
crimes
# Map data
# install.packages("maps") remember to install these two packages if you
# install.packages("mapproj") do not have them yet
library(mapproj)
library(maps)
states_map <- map_data("state")
states_map
# Merge datasets together
crime_map <- merge(states_map, crimes, by.x = "region", by.y = "state")
# After merging, the order has changed, which leads to polygons drawn
# in the incorrect order. Let's sort it
crime_map
library(dplyr) # for arrange() function
# Sort by group, then order
crime_map <- arrange(crime_map, group, order)
crime_map
# Now data can be plotted
library(ggplot2)
plot1 <- ggplot(crime_map, aes(x = long, y = lat, group = group, fill = Assault)) +
geom_polygon(colour = "black") +
coord_map("polyconic")
plot1
# Add title
plot1 <- plot1 +
ggtitle(" Proportion of crimes in the USA")
plot1
# Improve on colours
plot1 <- plot1 +
scale_fill_gradient2(low = "#559999", mid = "grey", high = "#BB650B",
midpoint = median(crimes$Assault))
plot1
# If you want white transparent backgroud only
plot1 <- plot1 +
theme_void()
plot1
# Note: if RStudio gives you this error when ploducing plot, then use this and try
# again
devAskNewPage(ask = FALSE)
# Special thanks to Winston Chang and other ggplot developers at RStudio who made made
# many of these codes