This article describes how to label states on a Geographic Map visualization. While this specific example labels US states, the same process can be modified to add labels on any kind of map based on latitude and longitude coordinates.
This examples goes from a Geographic Map of the US without labels:
To a map with labels on each state:
Requirements
- A Displayr document with a Geographic Map using the leaflet map package (see How to Create a Geographic Map).
- A table of your labels along with latitude and longitude coordinates for each. Many times you can find lists of commonly referenced geographic points and their coordinates through googling. This example uses population data from the US census imported into Displayr and a table of state names/abbreviations with their corresponding latitude and longitude coordinates that can be downloaded here.
Method
- Create the table with the State, lat, long, and stat abbreviation to use to create the labels. Click the Table down arrow > Paste or Enter Table.
- Click on the Paste or type data button.
- Copy the data in this excel file for state labels and their lat/long and paste it in the window. Click OK. Your label reference table should look like so:
- Change the Properties > GENERAL > Name of this table to states and click Hide.
- Now let's use the table to modify the map. Click on the map, ensure Chart > APPEARANCE > Map package is leaflet.
- Go to the Properties > R CODE box and add a line to the bottom.
- You'll be prompted with a message that says if you edit the R code we don't guarantee it will work with your custom code. Click Yes.
-
Paste the following code on the new empty line at the bottom of the R CODE and change chart in
chart$htmlwidget
(bolded below) to the name of the chart made by the visualization (check Properties > GENERAL > Name):#load the leaflet functions
library(leaflet)
#pull off the htmlwidget to edit
#change chart to the name of this specific map
new.chart = chart$htmlwidget
#bring the states labeling info into R
states = as.data.frame(states)
#loop through each state and use a function to add in the label
for (j in 1:nrow(states)) {
new.chart = addLabelOnlyMarkers(map = new.chart,
lng = as.numeric(states[j, "long"]),
lat = as.numeric(states[j, "lat"]),
label = states[j, "abbr"], #if you want the full state name change abbr to state
labelOptions = labelOptions(noHide = T, opacity = 0.75, textsize = "8px", direction = "center", textOnly = TRUE))
}
#call the new chart with all the labels appended
new.chart - Click Calculate.
- [Optional]: Edit the lat/long columns in your states table to tweak the placement of labels in your map.
- [Optional]: You can change the labels in the abbr column to something entirely different if you require different labels.
Next
How to Set Initial Zoom and Position of Geographic Maps
How to Create Small Multiples (Facet, or Panel) Visualizations