By Data Tricks, 27 September 2017
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.
library(plotly) 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) print(p)
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) print(p)
Note that the GDP values have been multiplied by 10 so that the bubbles are not too small.
Please note that your first comment on this site will be moderated, after which you will be able to comment freely.
You might also like
Violin plot in plotly
Interactive violin plot using plotly in R
Creating Maps in R (2019)
Creating a heatmap of the UK in R
Leaflet maps in R
Create interactive location maps in R and embed onto websites or other applications.
UK population density map in R
Create a unique population density map of the UK in R using ggplot2 and geom_point.
Exploring the randomness in pi with a random walk inspired visual
Access more for free
Access more articles and code for free