3D world map with plotly

By Data Tricks, 27 September 2017

Last modified 3 February 2019

1 Load packages and read in the data

There are many sources of world map data. Github https://github.com/plotly/datasets has some useful and fun datasets to practice on. For the purposes of this tutorial we’ll use the 2014 world GDP dataset.

df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
df[,2] <- as.numeric(df[,2])
df[,2] <- log(df[,2])

Note that the GDP values in column 2 of the dataframe have been transformed to a log scale. This is because there are some large outliers in the GDP data which makes it difficult to distinguish between many countries as they will be shaded in very similar colours.

2 Define the appearance of the map

Purely for code aesthetics, we’ll create a couple of variables containing information about the appearance of the map.

#Set country boundaries as light grey
l <- list(color = toRGB("#d1d1d1"), width = 0.5)
#Specify map projection and options
g <- list(
     showframe = FALSE,
     showcoastlines = FALSE,
     projection = list(type = 'orthographic'),
     resolution = '100',
     showcountries = TRUE,
     countrycolor = '#d1d1d1',
     showocean = TRUE,
     oceancolor = '#c9d2e0',
     showlakes = TRUE,
     lakecolor = '#99c0db',
     showrivers = TRUE,
     rivercolor = '#99c0db')

3 Plot the map

Finally, we can plot the data on to a 3D globe using the plot_geo command in plotly.

p <- plot_geo(df) %>%
     add_trace(z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Reds',
     text = ~COUNTRY, locations = ~CODE, marker = list(line = l)) %>%
     colorbar(title = 'GDP (log)') %>%
     layout(title = '', geo = g)

Extra layers can be added, for example adding bubbles to represent the GDP values using add_trace:

p <- plot_geo(df) %>%
     add_trace(opacity = 0.5, locations = ~CODE, colors = 'Reds', marker = list(size=~(10*GDP..BILLIONS.)), type="scattergeo", mode="markers") %>%
     add_trace(z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Reds', text = ~COUNTRY, locations = ~CODE, marker = list(line = l)) %>%
     colorbar(title = 'GDP (log)') %>%
     layout(title = '', geo = g)

Note that the GDP values have been multiplied by 10 so that the bubbles are not too small.

Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that your first comment on this site will be moderated, after which you will be able to comment freely.