- author: BugBytes
Using Streamlit Maps for Plotting Geographical Data
In a data science context, working with geographical data is a common task. Often, you may find the need to plot points on a map. In this article, we will explore how to use Streamlit maps to plot points on a map. We will also touch upon the caching tools provided by Streamlit.
Introduction
Before we dive into the details, let's take a look at the dataset we will be using for this demonstration. The dataset contains information about electric vehicle charging stations in the U.S state of Connecticut. We have worked with this dataset in a previous video, and we will be referencing it throughout this article.
Extracting Latitude and Longitude
To begin, we need to extract the latitude and longitude values from the dataset. In our script, we have defined a function called read_data
that reads the dataset and splits the last column, which contains the textual representation of latitude and longitude, into separate latitude and longitude values. The function returns a list of dictionaries, with each dictionary representing an electric vehicle charging station along with its latitude and longitude.
Native Integration with Streamlit Maps
Now that we have extracted the latitude and longitude values, we can proceed to plot these points on a map using Streamlit. To do this, we need to make sure Streamlit is installed in our environment. We can use the pip install streamlit
command to install it. Once installed, we can import the Streamlit library and use the streamlit.map
function to create a map with the points.
The streamlit.map
function creates a scatter plot chart on top of a map, using the latitude and longitude values from the dataset. The function takes the data as its first argument and accepts additional arguments such as zoom level and container width. The data can be provided as a DataFrame, a NumPy array, a PySpark DataFrame, or any iterable such as a Python list. In our case, we will pass the list of dictionaries containing latitude and longitude values.
Creating the Streamlit Application
To visualize the map with the plotted points, we need to create a Streamlit application. We can use the Streamlit command line tool, which is available after installing Streamlit, to run the Python file representing our Streamlit application. In our case, we will run the stations.py
script.
Upon running the Streamlit application, a browser page will open with the map centered around the state of Connecticut in the US. Each electric vehicle charging station will be represented by a red dot on the map. The map is created using OpenStreetMap as the base layer, and the scatter plot points are overlaid on top of it.
Caching with Streamlit
Streamlit executes the script from top to bottom for every user interaction or code change. This execution model makes development easy, but it can have performance implications. Long-running functions will rerun for each interaction, and objects will be recreated, making it difficult to persist them across reruns or sessions.
Streamlit provides a built-in caching mechanism to tackle these challenges. We can use the @streamlit.cache_data
decorator to cache the result of a function. In our case, we can decorate the read_data
function with the @streamlit.cache_data
decorator. This caching decorator ensures that the function is only executed when the input parameters or the code inside the function change. If the inputs and code remain the same, the cached result is retrieved from memory rather than re-executing the function.
By utilizing caching, we can prevent long-running functions from running repeatedly and improve the performance of our Streamlit application.
Caching Utilities in Streamlit
In Streamlit, there are two decorators provided for caching computations: @cache_data
and @cache_resource
. The @cache_data
decorator is recommended for caching computations that return data, such as working with a pandas DataFrame, numpy array, or Python iterable. On the other hand, the @cache_resource
decorator is recommended for caching global resources like machine learning models or database connections.
Benefits of Caching
The caching utilities in Streamlit offer several advantages for improving application performance. When a function is first called with specific parameters and function code, Streamlit checks if the values exist in the cache. If they don't, the function is executed and the return value is stored in the cache. The next time the function is called with the same parameters and code, it fetches the value from the cache directly, significantly speeding up the process. This is especially beneficial for functions that require significant time to execute, such as parsing or crunching large amounts of data.
Leveraging Third-Party Libraries
One way to extend the capabilities of Streamlit is by leveraging third-party libraries, referred to as components. These components provide additional functionalities that can be integrated seamlessly with Streamlit. For instance, one popular component is Folium, which allows you to create interactive maps in Streamlit applications.
To use Folium in a Streamlit application, you first need to install the streamlit-folium
library. This can be achieved by running the command pip install streamlit-folium
in your terminal. Once installed, you can import the folium
module and create a folium.Map
object, specifying the center and zoom level for the map. To render the Folium map in your Streamlit application, you will need to use the streamlit-folium
component, which can be imported using the StreamlitFolium
class.
By integrating Folium with Streamlit, you can enhance your application with interactive and visually appealing map visualizations. Additionally, there are numerous other components available for Streamlit that provide a wide range of functionalities such as building graphs and integrating with tools like Disqus or Volume. You can explore these components in the Streamlit Component Gallery.
Example: Integrating Folium in a Streamlit Application
Let's illustrate how Folium can be integrated into a Streamlit application using an example. Suppose we have a Streamlit application that reads data and plots a scatter plot using PyDeck. Instead of using PyDeck, we can use Folium and the streamlit-folium
component.
- Import the
folium
module and create afolium.Map
object. - Install the
streamlit-folium
library usingpip install streamlit-folium
. - Import the
StreamlitFolium
class from thestreamlit-folium
component. - Replace the
streamlit.map
call with theStreamlitFolium
component, passing in the Folium map object as the argument.
With these modifications, we can leverage the features provided by Folium to create map visualizations in our Streamlit application.
Using Streamlit to Create Folium Maps
In this article, we will explore how to use Streamlit, a powerful Python library for building interactive web applications, to create interactive maps with Folium, a Python library based on Leaflet.js.
Setting up the Environment
Before we begin, make sure you have Streamlit and Folium installed in your Python environment. You can install them using the following commands:
pipinstallstreamlit
pipinstallfolium
Creating the Map
To start, we need to import the necessary libraries and set up the Streamlit application. First, create a new Python file called app.py
and import the required libraries:
importstreamlitasstimportfoliumimportpandasaspd
Next, we can define our Streamlit application by using the st.title()
function to set the title of our app:
st.title('Electric Vehicle Charging Stations in Connecticut')
Now, let's load the data containing the electric vehicle charging stations in Connecticut. We can use the pd.read_csv()
function to read the data from a CSV file:
data=pd.read_csv('charging_stations.csv')
To display the map, we can use the st.folium_chart()
function and pass in a folium map object. Let's create a folium map centered on Connecticut:
map=folium.Map(location=[41.6032,-73.0877],zoom_start=7,width=700)
We can now run the Streamlit application by using the streamlit run
command:
streamlitrunapp.py
After running the application, you will see a folium map displayed in your browser, centered on Connecticut.
Adding Markers to the Map
Currently, the map doesn't have any markers on it. Let's add markers for each electric vehicle charging station in the data. To do this, we need to loop through the data and add a marker for each station.
forstationindata:location=(station['latitude'],station['longitude'])marker=folium.Marker(location=location)marker.add_to(map)
By iterating over each station in the data, we extract the latitude and longitude and store them in a tuple called location
. We then create a folium marker object using the location tuple and add it to the map.
Save the file and refresh the page to see the markers on the map for each charging station.
Adding Pop-ups to the Markers
To make the map more informative, let's add pop-ups to the markers that display the name of each charging station. We can extract the station names from the station_name
column in the CSV file.
forstationindata:location=(station['latitude'],station['longitude'])marker=folium.Marker(location=location,popup=station['station_name'])marker.add_to(map)
Now, when you click on a marker, a pop-up will appear displaying the name of the charging station.
In this article, we explored how to use streamlit maps to plot points on a map. we learned how to extract latitude and longitude values from a dataset and plot them using the streamlit.map
function. additionally, we discussed the caching mechanism provided by streamlit to optimize the performance of our application. streamlit is a powerful tool for visualizing geographical data and creating interactive applications with ease.
further reading
In this article, we explored how to create interactive maps using Streamlit and Folium. We learned how to set up the environment, load data, display maps, add markers, and add pop-ups to the markers. Streamlit and Folium provide an easy and powerful way to create interactive visualizations in Python.
If you found this article helpful, please consider subscribing to our channel for more content on Folium and Leaflet.js. We welcome any suggestions for future videos or articles in the comments section. Thank you for watching!