Я хочу создать карту США в R с цветом состояний, закодированным в виде карты тепла, основанной на метрике. Я знаю, как это сделать с помощью googleVis api, но я не могу использовать код и без опрокидывания это не так уж и здорово. Каков самый быстрый способ сделать это? Я знаком с пакетом карт, но я не могу заставить цвета сотрудничать. Я считаю, что это называется choropleth map.
Географическая карта тепла в R
Ответ 1
В пакете ggplot2 имеется полный пример, см. ?map_data
.
library(ggplot2)
example(map_data)
Ответ 2
(надеюсь, ответ может по-прежнему быть полезным для кого-то)
RevolutionAnalytics имеет отличный пример визуализации карты с помощью функции spplot()
. Здесь изображение оттуда:
Ответ 3
В пакете UScensus2000tract имеется пример cloropleth, основанный на популяции.
Ответ 4
Код
# 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 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