在ggplot中的地图上绘制饼图 [英] plotting pie graphs on map in ggplot

查看:543
本文介绍了在ggplot中的地图上绘制饼图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愿望清单的东西,不确定(即可能需要创建 geom_pie 才会发生这种情况)。我今天看到一张地图()中对我的回应县名将有助于这一概念。



我们如何使用ggplot2制作地图?



一个数据集和没有饼图的地图:

  load(url(http:// dl.dropbox.com/u/61803503/nycounty.RData))
head(ny); head(key)#从我的下拉框中查看数据集
library(ggplot2)
ggplot(ny,aes(long,lat,group = group))+ geom_polygon(color ='black',fill = NA)

#现在我们如何绘制每个县的比赛饼图
#(饼图的大小也可以通过大小
#参数控制,就像其他的`geom_`函数)。

预先感谢您的想法。

编辑:我刚刚在



我已经使用了以下资源来完成此操作(链接将提供更多细节) :


  1. ggtree博客

  2. 移动ggplot图例

  3. 正确的ggtree版本

  4. 以多边形为中心

以下是代码:

  load(url(http://dl.dropbox.com/ U / 618035 03 / nycounty.RData))
head(ny);头(键)#从我的下拉框中查看数据集

if(!require(pacman))install.packages(pacman)
p_load(ggplot2,ggtree,dplyr ,tidyr,sp,maps,pipeR,grid,XML,gtable)

getLabelPoint< - function(county){polygon(县[c('long','lat')])@ labpt }

df< - map_data('county','new york')#NY地区县数据
质心< - by(df,df $ subregion,getLabelPoint)#返回列表
centroids< - do.call(rbind.data.frame,centroids)#转换为数据框
名称(质心)< -c('long','lat')#适当的标题

弹出< - http://data.newsday.com/long-island/data/census/county-population-estimates-2012/%>%
readHTMLTable (1)%%>%
tbl_df()%>%
select(1:2)%>%
setNames(c(region,population) )%>%
mutate(
population = {as.numeric(gsub(\\D,,population))},
区域= tolower(gsub(\\s + [Cc] ounty | \\。,,region)),
#weight =((1 - (1 /(1 + exp人口/总和(人口))))/ 11)
权重= exp(人口/总和(人口)),
权重= sqrt(权重/总和(权重))/ 3



race_data_long< - add_rownames(centroids,region)%>>%
left_join({distinct(select(ny,region:other))} )%>>%
left_join(pops)%>>%
(〜race_data)%>>%
gather(race,prop,white:other)% >%
split(。,。$ region)

pies< - setNames(lapply(1:length(race_data_long),function(i){
ggplot(race_data_long aes(x = 1,prop,fill = race))+
geom_bar(stat =identity,width = 1)+
coord_polar(theta =y)+
theme_tree()+
xlab(NULL)+
ylab(NULL)+
theme_transparent()+
theme(plot.margin = unit(c(0, 0,0,0),mm))
}),名称( )


e1 < - ggplot(race_data_long [[1]],aes(x = 1,prop,fill = race))+
geom_bar(stat = 身份,宽度= 1)+
coord_polar(theta =y)

leg1 < - gtable_filter(ggplot_gtable(ggplot_build(e1)),guide-box)


p < - ggplot(ny,aes(long,lat,group = group))+
geom_polygon(color ='black',fill = NA)+
theme_bw()+
annotation_custom(grob = leg1,xmin = -77.5,xmax = -78.5,ymin = 44,ymax = 45)



n < ; - 长度(饼)

(i在1:n){

nms < - 名称(pies)[i]
dat < - race_data [其中(race_data $ region == nms)[1],]
p < - subview(p,pies [[i]],x = unlist(dat [[long]])[1] ,y = unlist(dat [[lat]])[1],dat [[weight]],dat [[weight]])

}

print(p)


This may be a wish list thing, not sure (i.e. maybe there would need to be the creation of geom_pie for this to occur). I saw a map today (LINK) with pie graphs on it as seen here.

I don't want to debate the merits of a pie graph, this was more of an exercise of can I do this in ggplot?

I have provided a data set below (loaded from my drop box) that has the mapping data to make a New York State map and some purely fabricated data on racial percentages by county. I have given this racial make up as a merge with the main data set and as a separate data set called key. I also think Bryan Goodrich's response to me in another post (HERE) on centering county names will be helpful to this concept.

How can we make the map above with ggplot2?

A data set and the map without the pie graphs:

load(url("http://dl.dropbox.com/u/61803503/nycounty.RData"))
head(ny); head(key)  #view the data set from my drop box
library(ggplot2)
ggplot(ny, aes(long, lat, group=group)) +  geom_polygon(colour='black', fill=NA)

#  Now how can we plot a pie chart of race on each county 
#  (sizing of the pie would also be controllable via a size 
#  parameter like other `geom_` functions).

Thanks in advance for your ideas.

EDIT: I just saw another case at junkcharts that screams for this type of capability:

解决方案

Three years later this is solved. I've put together a number of processes together and thanks to @Guangchuang Yu's excellent ggtree package this can be done fairly easily. Note that as of (9/3/2015) you need to have version 1.0.18 of ggtree installed but these will eventually trickle down to their respective repositories.

I've used the following resources to make this (the links will give greater detail):

  1. ggtree blog
  2. move ggplot legend
  3. correct ggtree version
  4. centering things in polygons

Here's the code:

load(url("http://dl.dropbox.com/u/61803503/nycounty.RData"))
head(ny); head(key)  #view the data set from my drop box

if (!require("pacman")) install.packages("pacman")
p_load(ggplot2, ggtree, dplyr, tidyr, sp, maps, pipeR, grid, XML, gtable)

getLabelPoint <- function(county) {Polygon(county[c('long', 'lat')])@labpt}

df <- map_data('county', 'new york')                 # NY region county data
centroids <- by(df, df$subregion, getLabelPoint)     # Returns list
centroids <- do.call("rbind.data.frame", centroids)  # Convert to Data Frame
names(centroids) <- c('long', 'lat')                 # Appropriate Header

pops <-  "http://data.newsday.com/long-island/data/census/county-population-estimates-2012/" %>%
     readHTMLTable(which=1) %>%
     tbl_df() %>%
     select(1:2) %>%
     setNames(c("region", "population")) %>%
     mutate(
         population = {as.numeric(gsub("\\D", "", population))},
         region = tolower(gsub("\\s+[Cc]ounty|\\.", "", region)),
         #weight = ((1 - (1/(1 + exp(population/sum(population)))))/11) 
         weight = exp(population/sum(population)),
         weight = sqrt(weight/sum(weight))/3
     )


race_data_long <- add_rownames(centroids, "region") %>>%
    left_join({distinct(select(ny, region:other))}) %>>%
    left_join(pops) %>>%
    (~ race_data) %>>%
    gather(race, prop, white:other) %>%
    split(., .$region)

pies <- setNames(lapply(1:length(race_data_long), function(i){
    ggplot(race_data_long[[i]], aes(x=1, prop, fill=race)) +
        geom_bar(stat="identity", width=1) + 
        coord_polar(theta="y") + 
        theme_tree() + 
        xlab(NULL) + 
        ylab(NULL) + 
        theme_transparent() +
        theme(plot.margin=unit(c(0,0,0,0),"mm"))
}), names(race_data_long))


e1 <- ggplot(race_data_long[[1]], aes(x=1, prop, fill=race)) +
        geom_bar(stat="identity", width=1) + 
        coord_polar(theta="y") 

leg1 <- gtable_filter(ggplot_gtable(ggplot_build(e1)), "guide-box") 


p <- ggplot(ny, aes(long, lat, group=group)) +  
    geom_polygon(colour='black', fill=NA) +
    theme_bw() +
    annotation_custom(grob = leg1, xmin = -77.5, xmax = -78.5, ymin = 44, ymax = 45) 



n <- length(pies)

for (i in 1:n) {

    nms <- names(pies)[i]
    dat <- race_data[which(race_data$region == nms)[1], ]
    p <- subview(p, pies[[i]], x=unlist(dat[["long"]])[1], y=unlist(dat[["lat"]])[1], dat[["weight"]], dat[["weight"]])

}

print(p)

这篇关于在ggplot中的地图上绘制饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆