In this quick project, I wanted to delve a bit deeper into interactive maps and build a coropleth map of countries and their GDP :
We start by loading the plotly package
library(plotly)
I found a premade data frame that gives GDP and geo-codes for countries, which is enough for the built-in parameters of plotly.
# Opening Github dataframe with countries that icludes GDP and Geo codes
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
head(df)
## COUNTRY GDP..BILLIONS. CODE
## 1 Afghanistan 21.71 AFG
## 2 Albania 13.40 ALB
## 3 Algeria 227.80 DZA
## 4 American Samoa 0.75 ASM
## 5 Andorra 4.80 AND
## 6 Angola 131.40 AGO
# boundary colour
bound_col <- list(color = toRGB("grey"), width = 0.5)
We’ll just put 2 parameters.
We want the interactive window to be borderless (showframe = F) and the projection to be a default mercator world map.
# map options
g <- list(
showframe = F,
projection = list(type = 'Mercator')
)
# plot
fig <- plot_geo(df)
fig <- fig %>% add_trace(
z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Blues',
text = ~COUNTRY, locations = ~CODE, marker = list(line = bound_col)
)
# title and legend config
fig <- fig %>% colorbar(title = 'GDP in Billions US$', tickprefix = '$')
fig <- fig %>% layout(
title = 'Global GDP by country',
geo = g
)
fig