plotly Map in R (3 Examples)
Hi! This tutorial will show you how to make plotly maps in the R programming language.
Here is an overview:
Let’s dive into the R code!
Install & Load plotly & dplyr Libraries
We will need to install and load the R plotly library, so that we can have access to its plot-building functions, including the ones we will make use of in this tutorial.
We will also have to install and load the R dplyr library as well, which is the foremost library in R for data analysis and manipulation. Also, the dplyr library allows us to make use of the pipe operator to pipe lines of code together and run them as a chunk.
Therefore, in your favorite R coding IDE, run the lines of code below to install and load plotly and dplyr:
# install plotly & dplyr install.packages(c("plotly", "dplyr")) # load plotly & dplyr library(plotly) library(dplyr)
We will make use of different datasets in this tutorial because of their unique properties, which are best suited for each kind of map. After downloading a dataset, you can preview its first 10 rows by running
df |> head(10).
Example 1: Plot Scatterplot on Map
In this example, we will plot a scatterplot on a map. Run the script below to create the visualization:
# fetch the data df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv') # geo styling g <- list( scope = 'usa', projection = list(type = 'albers usa'), showland = TRUE, landcolor = toRGB("gray95"), subunitcolor = toRGB("gray85"), countrycolor = toRGB("gray85"), countrywidth = 0.5, subunitwidth = 0.5 ) fig <- plot_geo(df, lat = ~lat, lon = ~long) |> add_markers( text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"), color = ~cnt, symbol = I("pentagon"), size = I(30), hoverinfo = "text" ) |> colorbar(title = "Incoming flights<br />February 2011") |> layout(title = "Most trafficked US airports", geo = g) fig
Next, we wrote the style for the map, which is a list comprising all the configurations of the map, such as the scope, projection, land color, etc. The toRGB() function converts R colors to hexadecimal colors, which are used in the styling of the map.
Then, we used the plot_geo() function to build the map, wherein we parsed the dataframe and defined the longitude and latitude of the map. We then piped the add_markers() function, in which we defined the text, color, symbol, and size arguments.
As for symbol and size, we used the I() function, which changes the class of an object to indicate that it should be treated ‘as is’, to specify the symbol and size of the scatterplot points. This will ensure that the class of the character strings parsed will remain unchanged.
Finally, we ran the plotly figure object to render the interactive map.
Example 2: Build Choropleth Map with GeoJSON
In this example, we will build a choropleth map using a GeoJSON file. First, though, we will need to install and load the rjson library, which we can use to read JSON files in R. Then, we will download and read the GeoJSON file and the CSV file from GitHub:
# install rjson install.packages("rjson") # load rjson library(rjson) # fetch data url <- "https://raw.githubusercontent.com/plotly/datasets/master/election.geojson" geojson <- rjson::fromJSON(file=url) url2<- "https://raw.githubusercontent.com/plotly/datasets/master/election.csv" df <- read.csv(url2) g <- list( fitbounds = "locations", visible = FALSE) fig <- plot_ly() |> add_trace( type="choropleth", geojson=geojson, locations=df$district, z=df$Coderre, colorscale="Blues", featureidkey="properties.district") |> layout(geo = g) |> colorbar(title = "Coderre Votes") |> layout(title = "2013 Montreal Election") fig
In the above example, we, first of all, downloaded and read the necessary files, then we defined the map configurations in a list, which includes the map’s fitbounds, and visibility, which was set to FALSE. The fitbounds is used to determine and set the boundaries of the map.
Next, the plot_ly() function and the add_trace() function are used to build the plotly map figure. A number of key arguments are defined in the
add_trace() function, including the type of the map (“choropleth”), GeoJSON file, locations, color scale, and feature id key. As in the previous example, the map configurations are implemented in the
Example 3: Build Choropleth Map with Built-in Country Geometry
In this final example, we will build a choropleth map with built-in country geometry. We will only need to download and read the 2014 World GDP dataset, which will be displayed over the map:
# fetch data df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv") fig <- plot_ly(df, type = "choropleth", locations = df$CODE, z = df$GDP..BILLIONS., text = df$COUNTRY, colors = "viridis") |> layout(title = "2014 Global GDP") fig
In the example above, we defined a number of arguments in the
plot_ly() function, such as type (“choropleth”), locations, which we defined using the CODE column in the dataset, “z”, which takes the numerical value to be displayed in the hover info, text, which is also displayed in the hover info, and colors, to which can parse any of the acceptable color palettes.
In this example, we did not have to download a GeoJSON file, because we used the built-in world country geometry.
Video, Further Resources & Summary
Do you need more explanations on how to make plotly maps in R? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain in some more detail how to make plotly maps in R.
The YouTube video will be added soon.
I hope you found this tutorial helpful! If yes, then make sure to check out other interesting R plotly tutorials on Statistics Globe, such as these ones:
- Create Dropdown Menu in plotly Graph in R (Example)
- plotly Sunburst Chart in R (3 Examples)
- plotly Bubble Chart in R (3 Examples)
- Learn R Programming
- plotly Pie & Donut Chart in R (4 Examples)
- How to Draw a plotly Area Chart in R (3 Examples)
This post has shown how to make plotly maps in R. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter