Сложность в настройке вывода картограмм в R Studio - PullRequest
0 голосов
/ 28 мая 2019

Я могу создать картограмму, используя cartogram :: cartogram_cont (), но у меня возникают трудности с настройкой стиля.

Я использовал broom :: tidy () и dplyr :: left_join (), чтобы укрепить картограмму, но я думаю, что стадия аккуратности помешала plotOrder. Если возможно, я включу выходные картограммы.

Я пытаюсь повторить этот тип вывода, но в моей местности. Plesae, обратите внимание, что набор данных, используемый для взвешивания в cartogram_cont (), не имеет особого значения, это просто подтверждение концепции на данном этапе:

[R Graph Gallery][1]
  [1]: https://www.r-graph-gallery.com/331-basic-cartogram/

Shapefile from: [Lle Shapefile Location][2]
  [2]: http://lle.gov.wales/catalogue/item/LocalAuthorities/?lang=en

library(dplyr)
library(leaflet)
library(maptools)
library(cartogram)
library(devtools)
install_github("HanOostdijk/odataR" , build_vignettes = T)
library(odataR)
library(tidyr)
library(rgdal)
library(htmltools)




#Read in shapefile and transform shape
#dsn = folder name, layer = filename but drop the .shp

shapefile <- readOGR(dsn = "Wales Shapefile",
                     layer = "localauthoritiesPolygon") %>% 
#Transform coordinate referencing system
spTransform(CRS("+init=epsg:4326")) 


#Next step is to join an interesting dataset to the shapefile using dplyr, then pass this to the cartoram package to render.
#Gone for the teacher sickness dataset from Stats Wales. Noticed it's only up to 2017, wonder if they've stopped collecting. 

teacher_sickness_data <- odataR_query('http://open.statswales.gov.wales/dataset/schw0001')


#Check values for join.
categories <- unique(teacher_sickness_data$Area_ItemName_ENG)
categories_shp <- shapefile@data$name_en

categories
categories_shp

#Teacher data has "All Welsh local authorities". Not contained in shapefile so remove. 

UA_sickness_data <- teacher_sickness_data[-c(2, 4:6, 8, 9, 11:13, 15:17)] %>% 
  filter(Area_ItemName_ENG != "All Welsh local authorities")


#Perform join to shapefile

shapefile_1 <- shapefile %>%
 merge(UA_sickness_data, by.x = "name_en", by.y = "Area_ItemName_ENG",
       duplicateGeoms = TRUE)

#Shiny App will allow choice of inputs to achieve one row per polygon. However, for testing
#functionality with cartograph functions, perform test filtering.

data_filtered <- UA_sickness_data %>% 
  filter(Year_ItemName_ENG == 2017) %>% 
  filter(Type_ItemName_ENG == "Full-time") %>% 
  filter(Variable_ItemName_ENG == "Total days of sick leave")

test_merge <- shapefile %>%
  merge(data_filtered, by.x = "name_en", by.y = "Area_ItemName_ENG")



nc_pal <- colorNumeric(palette = "Reds",
                       domain = log(test_merge@data$Data))

m <-test_merge %>% 
  leaflet() %>% 
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolygons(weight = 1,
              color = ~nc_pal(log(Data)),
              label = ~name_en,
              highlight = highlightOptions(weight = 3,
                                           color = "crimson",
                                           bringToFront = TRUE),
              popup = ~ paste0(Variable_ItemName_ENG, "<br/>",
                               "<b/>",
                               Data))

m

wales_cart <- cartogram_cont(test_merge, "Data", itermax=5)
plot(wales_cart)
[![Wales_Cartogram][3]][3]
[3]: https://i.stack.imgur.com/2tsMC.png


library(tidyverse)
library(ggmap)
library(broom)
library(rgeos) #used for gBuffer

#Buffer allows to tidy cartogram based on factor of choice. 
wales_cart_buffered <- gBuffer(wales_cart, byid=TRUE, width=0)


#tidy cartogram in order to pass to ggplot
spdf_fortified_wales <- tidy(wales_cart_buffered, region = "name_en")


#Now perform a join based on english UA names
spdf_fortified_wales_joined <- spdf_fortified_wales %>%
  left_join(. , wales_cart@data, by=c("id"="name_en")) 



ggplot() +
  geom_polygon(data = spdf_fortified_wales_joined, aes(fill = Data, x = long, y = lat, group = "name_en") , size=0, alpha=0.9) +
  coord_map() +
  theme_void()

[![incorrect_ggplot][4]][4]
[4]: https://i.stack.imgur.com/as0Z4.png

ggplot() +
  geom_polygon(data = spdf_fortified_wales_joined, aes(fill = Data, x = long, y = lat, group = "name_en") , size=0, alpha=0.9) +
  coord_map() +
  theme_void()
Success Criteria: Polygons are rendered correctly distorted and colour scale reflects weighting variable.



...