firmo23
firmo23

Reputation: 8454

Add country polygons to mapbox

I want to recreate a choropleth map with country polygons like the county level choropleth map here. And here is its result. enter image description here

I try to repeat the same procedure for a world map

library(ggplot2)
library(dplyr)
library(maps)
WorldData <- map_data('world') %>% filter(region != "Antarctica") %>% fortify

Country<-c("United States","Canada","France","Italy","Turkey","United States","Canada","France","Italy","Turkey")
Val<-c(50,67,89,567,9,50,67,89,567,9)
Name<-c('AD',"FGH","BGH","FGFG","EWRW",'ADy',"FGyH","BGyH","FGFyG","EyWRW")
Test<-data.frame(Country,Val,Name)
V1 <- aggregate(Val~Country,Test,sum)


colnames(WorldData)[5]<-"Country"
m2 <- data.frame(merge(V1,WorldData , by=c("Country"), all.x=T))


p <- m2 %>%
  group_by(group) %>%
  plot_mapbox(x = ~long, y = ~lat, color = ~Val1, colors = c('#ffeda0','#f03b20'),
              text = ~Country, hoverinfo = 'text', showlegend = FALSE) %>%
  add_polygons(
    line = list(width = 0.4)
  ) %>%
  add_polygons(fillcolor = ~Val1,
               line = list(color = 'black', width = 0.5),
               showlegend = FALSE, hoverinfo = 'none'
  ) %>%
  layout(
    xaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE),
    yaxis = list(title = "", showgrid = FALSE, showticklabels = FALSE),
    mapbox = list(
      style = 'light',
      zoom = 4,
      center = list(lat = ~median(lat), lon = ~median(long))),
    margin = list(l = 0, r = 0, b = 0, t = 0, pad = 0)
  )

p

but I get:

enter image description here

Upvotes: 0

Views: 304

Answers (1)

Chris
Chris

Reputation: 3996

I think you just need to order your data per the 'order' column in your data:

p <- m2 %>%
  arrange(order) %>%
  group_by(group) %>%
...
...

That worked for me.

Upvotes: 1

Related Questions