在ggplot2中使用choropleth贴图的栅格

在ggplot2中使用choropleth贴图的栅格,r,maps,ggplot2,R,Maps,Ggplot2,使用哈德利的伟大的ggplot2和他的书(第78-79页),我能够轻松地生成单choropleth地图,使用如下代码: states.df <- map_data("state") states.df = subset(states.df,group!=8) # get rid of DC states.df$st <- state.abb[match(states.df$region,tolower(state.name))] # attach state abbreviation

使用哈德利的伟大的ggplot2和他的书(第78-79页),我能够轻松地生成单choropleth地图,使用如下代码:

states.df <- map_data("state")
states.df = subset(states.df,group!=8) # get rid of DC
states.df$st <- state.abb[match(states.df$region,tolower(state.name))] # attach state abbreviations

states.df$value = value[states.df$st]

p = qplot(long, lat, data = states.df, group = group, fill = value, geom = "polygon", xlab="", ylab="", main=main) + opts(axis.text.y=theme_blank(), axis.text.x=theme_blank(), axis.ticks = theme_blank()) + scale_fill_continuous (name)
p2 = p + geom_path(data=states.df, color = "white", alpha = 0.4, fill = NA) + coord_map(project="polyconic")

states.df您可以为所需的分组添加两列并使用facet:

library(ggplot2)
library(maps)
d1 <- map_data("state")
d2 <- unique(d1$group)
n <- length(d2)
d2 <- data.frame( 
  group=rep(d2,each=6), 
  g1=rep(1:3,each=2,length=6*n),
  g2=rep(1:2,length=6*n),
  value=runif(6*n)
)
d <- merge(d1, d2,  by="group")
qplot(
  long, lat, data = d, group = group, 
  fill = value, geom = "polygon" 
) + 
  facet_wrap( ~ g1 + g2 )
库(ggplot2)
图书馆(地图)

d1我将在这里批量粘贴此脚本。它是自包含的,我只是生成一些任意的分类变量和一个随机的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)
rm(list=ls())
安装程序包(“ggplot2”)
图书馆(GG2)
安装程序包(“地图”)
图书馆(地图)
安装程序包(“mapproj”)
图书馆(mapproj)
安装程序包(“spatstat”)
图书馆(spatstat)
主题集(主题宽度(基本尺寸=8))
选项(scipen=20)

MyPalette我在寻找类似的东西,最后使用
gridExtra
包来排列几个choropleth地图。结果是以下曲线图,与Gelman的曲线图相似:

我将代码分为3个步骤:

首先:为每个类别创建choropleth贴图列表:

library(ggplot2)
library(dplyr)
library(maps)
library(gridExtra)
library(RGraphics)

# create a dataset ---- 
d1 <- map_data("state")
group_idx <- unique(d1$group)
n <- length(group_idx)
c1 = paste0("Income ", 1:5)
c2 = paste0("Age ", 1:4)
len_c1 = length(c1)
len_c2 = length(c2)
d2 <- data.frame( 
      group=sort(rep(group_idx, each=20)),
      g1=rep(c1, n*len_c1*len_c2),
      g2=rep(rep(c2, each=len_c1), n),
      value=runif(n*20)
)
d <- merge(d1, d2,  by="group")



# a list with several choropleth maps ----
plot_list <- lapply(1:len_c1, function(i) lapply(1:len_c2, function(j)
      # the code below produces one map for category1=i and category2=j
      ggplot(d[d$g1 == c1[i] & d$g2 == c2[j],])+
            geom_polygon(aes(x=long, y=lat, group=group, fill=value))+
            scale_fill_gradient(limits=c(min(d$value), max(d$value)))+
            # aesthetics and remove legends
            labs(x = NULL, y = NULL)+
            theme(line = element_blank(),
                  axis.text = element_blank(),
                  axis.title = element_blank(),
                  panel.background = element_blank(),
                  legend.position="none")
      )
)
库(ggplot2)
图书馆(dplyr)
图书馆(地图)
图书馆(gridExtra)
图书馆(RGraphics)
#创建数据集--

d1这也有效-expand.grid在这里执行与merge相同的工作。另外,这个答案有很多不错的小技巧和选择,我会选择的!谢谢,这很有效。关键是merge命令,它扩展了从map_数据中出现的数据帧,然后是facet_wrap选项,它的工作方式与ggplot2完全相同。谢谢
get_legend <- function(myggplot){
      tmp <- ggplot_gtable(ggplot_build(myggplot))
      leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
      legend <- tmp$grobs[[leg]]
      return(legend)
}
big_legend <- (ggplot(data.frame(x=1:4, y=runif(4)))+ 
                    geom_point(aes(x=x, y=y, fill=y))+
                    scale_fill_gradient(limits=c(min(d$value), 
                                                 max(d$value)), name="")+
                          theme(legend.position="bottom", 
                                legend.box = "horizontal")+
                    guides(fill = guide_colourbar(barwidth = 40, 
                                                  barheight = 1.5))) %>% 
      get_legend()
grid.arrange(big_legend)
# the plots can be organized using gridExtra:
grob_list <- lapply(1:len_c1, function(x) arrangeGrob(grobs=plot_list[[x]],
                                                      top = c1[x], ncol=1))

grob_c2 <- arrangeGrob(grobs=lapply(1:len_c2, function(x) textGrob(c2[x])), 
                       ncol=1, top = " ")

maps_arranged <- arrangeGrob(grobs=union(list(grob_c2), grob_list),nrow=1)

# A layout matrix to the final arrange - each row with maps takes 2 rows, 
# and the legend takes 1 row. The first grob (maps_arranged) have 6 cols,
# and the legend grob will ocupy 5 cols - lay is a (2*len_c2+1)x(len_c1+1) matrix
lay=matrix(1, nrow=2*len_c2+1, ncol=len_c1+1)
lay[9,1] <- NA
lay[9, 2:6] <- 2
grid.arrange(maps_arranged, big_legend, layout_matrix=lay)