Plot Points and Lines on Map with Plotly + Mapbox

Yuki Wakatsuki
4 min readFeb 6, 2022

--

Photo by GeoJango Maps on Unsplash

W hen you make map by yourself, we can easily imagine that the data points and lines are needed to understand where the target places are. With plotting the markers on your map, you can make maps which are more helpful and usable on your life.

Previously, I introduced how to show the map on Python with using Plotly and Mapbox here. In thi article, I will show how to plot points and lines on Map.

  1. Visualize base map

According to previous article, I plot map at first.

Photo by Yuki Wakatsuki on Github

2. Preprocess

a. Preparing data information

In here, I consider that plotting the 6 major Prefecture in Japan. I made the table with pandas.DataFrame as below.

import pandas as pdvalue = [
[“Hokkaido”,”43°03′51″”,”141°20′49″”],
[“Miyagi”,”38°16′08″”,”140°52′19″”],
[“Tokyo”,”35°41′22″”,”139°41′30″”],
[“Aichi”,”35°10′49″”,”136°54′24″”],
[“Osaka”,”34°41′11″”,”135°31′12″”],
[“Fukuoka”,”33°36′23″”,”130°25′05″”],
[“Okinawa”,”26°12′45″”,”127°40′52″”],
]
df = pd.DataFrame(value,columns=[“name”,”lat”,”lon”])

I prepared name of location(“name”), latitude(”lat”), longtitude(”lon”) columns.

b. Convert to coordinate.

Currently, latitude and longtitude are defined as DMS(Degrees minutes seconds). For example, Hokkaido latitude is indicated as 43 degree(North), 3 minute, and 51 second, longtitude is indicated as 141 degree(East), 20 minute, and 49 second. For plotting points, I will use the parameter ‘lat’ and ‘lon’ in plotly.graph_objects.Scattermapbox() , which expect input as coordinates value(See more detail).

I prepared the function for convert DMS data to corrdinate.

import redef to_int(df, col, re_str):
ret = df[col].apply(lambda x: re.findall(re_str, x)[0]).astype(int)
return ret
def decompose(df, col):
df[f"{col}_degree"] = to_int(df, col, "(.*[0-9][0-9])°")
df[f"{col}_minute"] = to_int(df, col, "°(.*[0-9][0-9])′")
df[f"{col}_second"] = to_int(df, col, "′(.*[0-9][0-9])″")
return df
def convert_coordinate(df, col):
df = decompose(df, col)
df[f"{col}_coordinate"] = df[f"{col}_degree"] + df[f"{col}_minute"] / 60 + df[f"{col}_second"] / 60 / 60
return df

Apply as below:

for col in [“lat”, “lon”]:
df = convert_coordinate(df, col)

The *_cordinate columns show the converted values. Now the value for location was cleaned for plotly.graph_objects.Scattermapbox().

3. Plot

a. points

By using data made in 2, I plotted figure same way in previous article.

import plotly.graph_objects as gofig = go.Figure()
fig.add_trace(go.Scattermapbox(
mode = "markers",
lat = df.lat_coordinate.tolist(),
lon = df.lon_coordinate.tolist(),
hovertext = df.name.tolist(),
marker = {'color': "red",
"size": 10},
))
fig.update_layout(margin ={'l':0,'t':0,'b':0,'r':0},
mapbox = {
'center': {'lon': 139, 'lat': 36.5},
'style': "stamen-terrain",
'zoom': 4.5},
width=1600,
height=900,)
fig.show()
Photo by Yuki Wakatsuki on Github

Now, you can see the 6 location points colored as red. I added parameter “mode”, “lat”, “lon”, “hovertext”, “marker”. “mode”: plotting object type, “lat”: latitude, “lon”: longtitude, “hovertext”: text on each maker, “maker”: marker propaties(work only ”markers” inclues in mode). “lat”, “lon”, “hovertext” are inputted as list. All value in list are plottted. You can see “hovertext” information when you move mouse the cursor on the point. You can conrfirm that these informarion are corresponding on map.

b. points + lines

To indicates the connection of each points, you may want to make line on map. It enables us to be more undestandable. Line plot is easily makable, you have to change “mode” only.

mode = "markers+lines",
Photo by Yuki Wakatsuki on Github

Points and Lines should be change by what you want to show. If you are thinking for marking the spot, like city address, store address, and your favorite spot, etc, points information is enough to understand. But if you are thinking for marking the spot connection, like traffic route, boundary, and river, etc, line makes us more easier to undetstand. Below is the one of example which I used points and lines differently. Highway is plotted as line, Interchange with point.

Photo by Yuki Wakatsuki on Github

In the future, I will introduce other object example on map.

--

--

Yuki Wakatsuki

a data scientist. Tokyo, Japan. Interested in data science, data analysis, data visualization, statistics, machine learning, hydrology.