Data Visualization with Python Folium Maps | by Becca R | Towards Data Science

One of my favorite things about data science is data visualization. I love creating and utilizing visual aids to support stories and trends from my data. Python Folium library has been a helpful resource for me to utilize the power of geospatial visual analysis. In other words, maps!
Maps allow me to analyze my data across several dimensions in a single visualization. For a recent project, I analyzed 293 U.S. cities to determine which would be good candidates for a pilot bike and scooter share program. Using OLS regression, I determined that, among other features, the congestion level of a city (measured by percent of driving time spent in traffic, obtained from INRIX.com) was positively and significantly correlated with the “bikeability” of a city (measured by walkscore.com’s bike score). While this result may seem counterintuitive, it is reasonable to think that people in more congested cities have an incentive to travel by bike (think: “I do not want to sit in traffic so I’m going to strap on my helmet and pedal myself to work”).
So how can I visualize the relationship between “bikeability” and congestion? A simple seaborn regplot shows a positive linear correlation between bike score and traffic (measured by percentage of driving time spent in traffic).
sns.set(style = 'white')sns.regplot(data=df, x="traffic_index", y="bike_score", ci = None)plt.xlabel('Percentage of driving time spent in traffic', size = 16)plt.ylabel('Bike score', size = 16)plt.title("City bike score and overall traffic level", size = 20, weight = 'bold')
FBut what if I wanted to visualize the geospatial distribution of cities across these two dimensions? Well... using geospatial analysis, I could create a map where cities with higher traffic AND higher bike scores were shown. Even better, changing attributes such as the color and size of map markers means that I can use one figure to visualize all three dimensions.
To create this map, I first installed the Python Folium library.
!conda install -c conda-forge folium=0.5.0 --yes import folium import webbrowser
The first dimension I wanted to show is geolocation. I set my map’s latitude and longitude based on the results of a simple Google search for “latitude and longitude of the US”. Then, I defined my map (cleverly named traffic_map) to initialize at these coordinates. The default zoom is set to five (I had to play around with this parameter until I found a good display).
latitude = 37.0902longitude = -95.7129traffic_map = folium.Map(location=[latitude, longitude], zoom_start=5)
The second dimension wanted to show is traffic congestion. I grouped my traffic variable (“traffic_index”) into quartiles:
df['traffic_index_quartile'] = pd.qcut(df['traffic_index'], 4, labels=False)
Next, I created a dictionary for the colors of my markers. I decided on a range of primary colors from lightblue (0) to red (3). I wanted the highest quartile (i.e. the most congested cities) to stand out with a bold red, and the lowest quartile (i.e. the least congested and least viable candidates) to more or less fade into the base-map.
colordict = {0: 'lightblue', 1: 'lightgreen', 2: 'orange', 3: 'red'}
Side note: I found viable color names from this Stack Overflow post:https://stackoverflow.com/questions/36202514/foilum-map-module-trying-to-get-more-options-for-marker-colors. I have tried most of the colors listed, and they have accurately displayed as their names suggest, except for “light red”, which either causes an error or shows up as black.
The third and final dimension on my map is city “bikeability”. To visualize this dimension, I set the size of the city markers to be 0.15 time the city’s bikescore (another parameter I had to play around with using trial and error until it “looked” right).
The complete code for the final map is as follows:
for lat, lon, traffic_q, traffic, bike, city in zip(df['latitude'], df['longitude'], df['traffic_index_quartile'], df['traffic_index'], df['bike_score'], df['city']):    folium.CircleMarker(        [lat, lon],        radius=.15*bike,        popup = ('City: ' + str(city).capitalize() + '<br>'                 'Bike score: ' + str(bike) + '<br>'                 'Traffic level: ' + str(traffic) +'%'                ),        color='b',        key_on = traffic_q,        threshold_scale=[0,1,2,3],        fill_color=colordict[traffic_q],        fill=True,        fill_opacity=0.7        ).add_to(traffic_map)traffic_map
Through this geospatial data visualization, we can quickly see two facts about cities and biking. First, “bikeability” is positively related to traffic congestion. Second, cities with high traffic AND “bikeability” (i.e. large red markers) are more likely to be found in the Northeast, California, and Pacific Northwest regions of the U.S. (with a few notable exceptions).
Check out my post about the full project here. And feel free to leave feedback or thoughts in the comments!