2

我有一个与R相关的问题。我正在尝试根据数值在地图上为不同国家/地区的区域着色。现在,我没有所有国家/地区的值,所以其中一些是空的。

Year    Country       Numeric
2009    Afghanistan   

像这样。因此,当我获得基于某个级别的值时,例如 >5、5-10 等。我想用不同的颜色填充它们。我怎么能在R中做到这一点?我在这方面花了很长时间,但没有取得重大进展。

我可以填写世界地图,但不能为我拥有的数据操作它。

> p <- ggplot(world, aes(long,lat,group=group)) + 
  geom_polygon(fill="darkgreen",colour="white") +
  theme(panel.background = element_rect(fill = "lightsteelblue2"))

任何建议和提示将不胜感激!

4

3 回答 3

3

您可以使用 rworldmap(它的优点是拥有现代地图,包括例如 S.Sudan 并且不包括例如苏联)。地图有 3 种分辨率(默认是最粗糙的,适用于全局地图。

library(rworldmap)

#example data including an NA
country <- c('Afghanistan','Albania','Algeria','Andorra','Angola','Antigua and Barbuda')
data <- c(NA, 8.53, 8.64, 21.25, 10.08, 9.07)

dF <- data.frame(country=country, data=data)

#join data to a map to create a spatialPolygonsDataFrame
sPDF <- joinCountryData2Map(dF, joinCode='NAME', nameJoinColumn='country')

#default map (see rworldmap documentation for options e.g. catMethod, numCats, colourPalette, mapRegion)
#missingCountryCol used for NA and countries not in the join file
mapCountryData(sPDF, nameColumnToPlot='data', missingCountryCol='dark grey')

rworldmap 图

于 2013-10-14T19:17:16.097 回答
2

包括fill作为您的一部分aes

library(maps)
world<-map_data("world")

set.seed(123)
w2<-data.frame(world,data=sample(10,length(unique(world$group)),T)[world$group])

ggplot(w2,aes(long,lat,group=group,fill=data))+
    geom_polygon(color="white")+
    scale_fill_gradient(low="lightgreen",high="darkgreen")+
    theme(panel.background = element_rect(fill = "lightsteelblue2"))

在此处输入图像描述

于 2013-10-12T14:36:12.293 回答
1

这基本上是我用来解决我需要做的事情的代码:

library(xlsx)
library(maps)
library(maptools)
library(mapproj)
library(mapdata)
library(rworldmap)
library(countrycode)

d <- read.xlsx("health_expenditure.xlsx",2)
d.df <- data.frame(d)
d.sub <- subset(d.df,Year=="2009")
w4 <- data.frame(d.sub$Country,data=d.sub$Numeric.Value)
colnames(w4)[1] <- "country"
w4$breaks <- cut(w4$data, 5)
w4$code <- countrycode(w4$country,"country.name","iso3c")
sPDF <- joinCountryData2Map(w4,joinCode="ISO3",nameJoinColumn="code")
par(mai=c(0,0,0.2,0),xaxs="i",yaxs="i")
mapDevice()
mapCountryData(mapToPlot=sPDF, nameColumnToPlot="breaks",missingCountryCol="white",oceanCol="lightsteelblue2",colourPalette="heat",mapTitle="Health Expenditure")

2009年卫生支出

于 2013-10-15T08:09:39.907 回答