格式化GGPLOT2地图(Format the ggplot2 map)

2019-08-17 10:25发布

我正尝试生产使用R.我想表明从巴西国人均GDP GGPLOT2一个世界地图。 有2个问题:

  1. 在国家的中心有两个标签是不容易读取信息。 他们overlapping.Reducing没有解决的数字。

  2. 我想改变颜色休息和不知道如何访问它。 我想用的颜色变得容易注意到GDP的个体差异。

我的数据是: https://docs.google.com/file/d/0B_coFit6AovfcEFkbHBjZEJaQ1E/edit

这里是我的代码:

library(maptools)
gpclibPermit()
library(ggplot2)
library(rgdal)
library(rgeos)
library(ggmap)


# read administrative boundaries (change folder appropriately)
brMap <- readShapePoly("BRASIL.shp")
brMap

# read downloaded data (change folder appropriately)
brRen <- read.csv("Renda.csv", sep = ";", quote = "\"", dec=".", stringsAsFactors = FALSE)
brRen$rendapc <- as.numeric(as.character(brRen$rendapc)) # format as numeric

#convert shp to UTF8
library(descr)
brMap$ESTADO<-toUTF8(brMap$ESTADO, "IBM850")

# convert shp data to data frame for ggplot
as.data.frame(brMap) # para definir a region
brMap = gBuffer(brMap, width=0, byid=TRUE) #correct problem with Polygons - TopologyException
brMapDf <- fortify(brMap, region="UF")
brMapDf


# merge map and data
brRenMapDf <- merge(brMapDf, brRen, by.x="id", by.y="Iden")
brRenMapDf <- brRenMapDf[order(brRenMapDf$order),]

# limit data to main Europe
brazil.limits <- geocode(c("Monte Caburaí", "Barra do Chuí", "Serra do Divisor", "Ilhas Martin Vaz"))
brRenMapDf <- subset(brRenMapDf, long > min(brazil.limits$lon) & long < max(brazil.limits$lon) & lat > min(brazil.limits$lat) & lat < max(brazil.limits$lat))

# ggplot mapping
# data layer
m0 <- ggplot(data=brRenMapDf)
# empty map (only borders)
m1 <- m0 + geom_path(aes(x=long, y=lat, group=group), color='gray') + coord_equal()
m1

# fill with education expenditure data
m2 <- m1 + geom_polygon(aes(x=long, y=lat, group=group, fill=rendapc))
m2


# inverse order (to have visible borders)
m0 <- ggplot(data=brRenMapDf)
m1 <- m0 + geom_polygon(aes(x=long, y=lat, group=group, fill=rendapc)) + coord_equal()
m2 <- m1 + geom_path(aes(x=long, y=lat, group=group), color='black')
m2


# over a GoogleMap (not working if not correctly projected)
map <- get_map(location = 'Brazil', zoom=4)
m0 <- ggmap(map)
m1 <- m0 + geom_polygon(aes(x=long, y=lat, group=group, fill=rendapc), data=brRenMapDf, alpha=.9)
m2 <- m1 + geom_path(aes(x=long, y=lat, group=group), data=brRenMapDf, color='black')
m2


# add text
library(doBy)
txtVal <- summaryBy(long + lat + rendapc ~ id, data=brRenMapDf, FUN=mean, keep.names=T)
m3 <- m2 + geom_text(aes(x=long, y=lat, label=rendapc), data=txtVal, col="yellow", hjust=0.5, vjust=0.5, cex=3)
m3

我的结果,我想提高:

Answer 1:

至于改变colorscale,GGPLOT2具有处理尺度的统一方式。 你总是在寻找函数的格式scale_{which_scale}_{scale_type}其中which_scale是一种审美(你在使用什么aes()例如fillsize ),并scale_type可连续或不连续的,等等。你所寻找的,如果你想调整的fill规模scale_fill_continuousscale_fill_gradient ,或scale_fill_gradient2 。 看看这些功能的文档。

一个代码示例:

m2 <- m1 + geom_polygon(aes(x=long, y=lat, group=group, fill=rendapc))
m2 + scale_fill_gradient(low = "blue", high = "red")


文章来源: Format the ggplot2 map