如何使用ggplot在NA值多边形中添加对角线?

时间:2016-11-01 06:28:19

标签: r ggplot2

我正努力根据强化的SPDF绘制巴基斯坦全国平均值的综合Z值偏差(一系列因子)。出于这个问题的目的,我的数据是无关紧要的。如有必要,我可以提供。

我正在使用 ggplot 来创建输出,其中命令和结果如下所示:

ggplot() + geom_polygon(data = plot.pakmod_sumZ, aes(x = long, y = lat, group = group, fill = SumZ.Cat), color = "black", size = 0.25, na.rm = TRUE) + scale_fill_manual(name = "Deviations from National Average", labels = c("-7", "-6", "-5", "-4", "-3", "-2", "-1", "Positive"), values = c("darkorange4","brown", "orangered1","tomato1","darkorange3","orange","yellow", "greenyellow"), na.value = "Grey", guide = guide_legend(reverse = TRUE)) + coord_map() + labs(x = NULL, y = NULL) + scale_x_discrete(breaks = NULL) + scale_y_discrete(breaks = NULL) + theme_minimal()

Deviations from National Average

我现在想弄清楚是否可以在多边形中添加对角线,这些多边形具有缺失值并且是灰色的。可以使用 ggplot 完成吗?

1 个答案:

答案 0 :(得分:0)

这是我从here获得的一个例子。我选择使用水平误差棒geom。请注意,这不是执行此操作的唯一方法。

library(ggplot2)
library(sp)
library(rgdal)
library(rgeos)

# create a local directory for the data
localDir <- "R_GIS_data"
if (!file.exists(localDir)) {
  dir.create(localDir)
}

# download and unzip the data
url <- "ftp://www.ecy.wa.gov/gis_a/inlandWaters/wria.zip"
file <- paste(localDir, basename(url), sep='/')
if (!file.exists(file)) {
  download.file(url, file)
  unzip(file,exdir=localDir)
}

# create a layer name for the shapefiles (text before file extension)
layerName <- "WRIA_poly"

# read data into a SpatialPolygonsDataFrame object
dataProjected <- readOGR(dsn=localDir, layer=layerName)

dataProjected@data$id <- rownames(dataProjected@data)

# create a data.frame from our spatial object
watershedPoints <- fortify(dataProjected)

# merge the "fortified" data with the data from our spatial object
watershedDF <- merge(watershedPoints, dataProjected@data, by = "id")

dataProjected@data$id <- rownames(dataProjected@data)

watershedPoints <- fortify(dataProjected)

watershedDF <- merge(watershedPoints, dataProjected@data, by = "id")

ggWatershed <- ggplot(data = watershedDF, aes(x=long, y=lat, group = group, fill = WRIA_NM)) +
  geom_polygon()  +
  geom_path(color = "white") +
  scale_fill_hue(l = 40) +
  coord_equal() +
  theme(legend.position = "none", title = element_blank())

# Adding coordinates to the data part of SPDF. `sd` is the variable of interest
# which is beign plotted here. Each line extends sd away from long coordinate
dataProjected@data$sd <- rnorm(nrow(xy), mean = 50000, sd = 10000)
xy <- coordinates(dataProjected)
dataProjected@data$long <- xy[, 1]
dataProjected@data$lat <- xy[, 2]

ggWatershed + 
    geom_errorbarh(data = dataProjected@data, aes(group = id, xmin = long - sd, xmax = long + sd))

enter image description here