Я просто вставлю этот скрипт сюда оптом.Он самодостаточен, и я просто генерирую некоторые произвольные категориальные переменные и случайное DV, по которому окрашиваются состояния.В коде есть некоторые вещи, которые не нужны;мои извинения за это.
rm(list = ls())
install.packages("ggplot2")
library(ggplot2)
install.packages("maps")
library(maps)
install.packages("mapproj")
library(mapproj)
install.packages("spatstat")
library(spatstat)
theme_set(theme_bw(base_size = 8))
options(scipen = 20)
MyPalette <- colorRampPalette(c(hsv(0, 1, 1), hsv(7/12, 1, 1)))
### Map ###
StateMapData <- map_data("state")
head(StateMapData)
### Some Invented Data ###
IndependentVariable1 <- c("Low Income", "Mid Income", "High Income")
IndependentVariable2 <- c("18-29", "30-44", "45-64", "65+")
# Here is one way to "stack" lots of copies of the shapefile dataframe on top of each other:
# This needs to be done, because (as far as I know) ggplot2 needs to have the state names and polygon coordinates
# for each level of the faceting variables.
TallData <- expand.grid(1:nrow(StateMapData), IndependentVariable1, IndependentVariable2)
TallData <- data.frame(StateMapData[TallData[, 1], ], TallData)
colnames(TallData)[8:9] <- c("IndependentVariable1", "IndependentVariable2")
# Some random dependent variable we want to plot in color:
TallData$State_IV1_IV2 <- paste(TallData$region, TallData$IndependentVariable1, TallData$IndependentVariable2)
RandomVariable <- runif(length(unique(TallData$State_IV1_IV2)))
TallData$DependentVariable <- by(RandomVariable, unique(TallData$State_IV1_IV2), mean)[TallData$State_IV1_IV2]
### Plot ###
MapPlot <- ggplot(TallData,
aes(x = long, y = lat, group = group, fill = DependentVariable))
MapPlot <- MapPlot + geom_polygon()
MapPlot <- MapPlot + coord_map(project="albers", at0 = 45.5, lat1 = 29.5) # Changes the projection to something other than Mercator.
MapPlot <- MapPlot + scale_x_continuous(breaks = NA, expand.grid = c(0, 0)) +
scale_y_continuous(breaks = NA) +
opts(
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.background = theme_blank(),
panel.border = theme_blank(),
expand.grid = c(0, 0),
axis.ticks = theme_blank(),
legend.position = "none",
legend.box = "horizontal",
title = "Here is my title",
legend.key.size = unit(2/3, "lines"))
MapPlot <- MapPlot + xlab(NULL) + ylab(NULL)
MapPlot <- MapPlot + geom_path(fill = "transparent", colour = "BLACK", alpha = I(2/3), lwd = I(1/10))
MapPlot <- MapPlot + scale_fill_gradientn("Some/nRandom/nVariable", legend = FALSE,
colours = MyPalette(100))
# This does the "faceting":
MapPlot <- MapPlot + facet_grid(IndependentVariable2 ~ IndependentVariable1)
# print(MapPlot)
ggsave(plot = MapPlot, "YOUR DIRECTORY HERE.png", h = 8.5, w = 11)