The ggplot2 geom_polygon mapping goes crazy after data merging

I am trying to create a grid containing maps of megaregions in us. I am creating a SpatialPolygonDataframe from a form file. then convert it to data.frame file to use ggplot2. as soon as I add data to the frame, polygon graphics. the file containing SpatialPolygon and the data frame is here: https://drive.google.com/open?id=1kGPZ3CENJbHva0s558vWU24-erbqWUGo the code looks like this:

load("./data.rda")
prop.test <- proptest.result[which(proptest.result$variable=="Upward N"),]

#transforming the data
# add to data a new column termed "id" composed of the rownames of data
shape@data$id <- rownames(shape@data)
#add data to our 
shape@data <- data.frame(merge(x = shape@data, y = prop.test, by.x='Name', by.y="megaregion"))

# create a data.frame from our spatial object
mega.prop <- fortify(shape)
#merge the "fortified" data with the data from our spatial object
mega.prop.test <- merge(mega.prop, shape@data, by="id")

Setting up the first (mega.prop) works fine:

ggplot(data = mega.prop, aes(x=long, y=lat, group=group), fill="blue")+
    geom_polygon()

graph before adding data info frame

but plot after adding analytics data:

ggplot(data = mega.prop.test, aes(x=long, y=lat, group=group), fill="blue")+
    geom_polygon()

The plot after adding analytical data

In the new plot:

  • Polygon filling is corrupted. (Is this about dot order? How?)
  • two of the polygons are completely missing.

What is the problem? Thank you so much for your help.

+2
1

geom_map() ( - ), /.

, , , .

, , . rgeos::gSimplify() , , .

library(ggplot2)
library(tidyverse)

shape_map <- tbl_df(fortify(shape, region="Name"))
colnames(shape_map) <- c("long", "lat", "order", "hole", "piece", "region", "group")

prop.test <- proptest.result[which(proptest.result$variable=="Upward N"),]

ggplot() +
  geom_map(data=shape_map, map=shape_map, aes(long, lat, map_id=region)) +
  geom_map(
    data=filter(prop.test, season=="DJF"),
    map=shape_map, aes(fill=prop.mega, map_id=megaregion)
  )

enter image description here

+3

Source: https://habr.com/ru/post/1692809/


All Articles