introduction
In the field of data analysis and visualization, map visualization is a very important skill. It can help us understand and present geospatial data more intuitively. Folium is a Python-based map visualization library. It is built on the ground, providing rich functions and easy-to-use interfaces, making map visualization in Python simple and efficient. This article will introduce in detail how to use Folium to visualize maps in Python, including installation, basic usage, advanced features, and real-life cases.
1. Introduction and installation of Folium
1. Introduction to Folium
Folium is a Python library that allows users to create and customize interactive maps through Python code. Folium is based on, an open source JavaScript library for creating interactive maps on web pages. Folium combines the ease of use of Python with its map functionality, making it simple and powerful to visualize maps in Python.
2. Install Folium
To use Folium, you need to install it first. You can use the pip command to install:
pip install folium
Once the installation is complete, you can import and use Folium for map visualization in Python.
2. Basic use
1. Create a map
Creating a map with Folium is very simple. You just need to create a Map object and specify the center point and zoom level of the map. Here is a sample code for creating an OpenStreetMap map:
import folium # Create a map, set the starting position and zoom levelm = (location=[39.9042, 116.4074], zoom_start=10) # Beijing's latitude and longitude # Show map(existJupyter NotebookShow directly in,或exist其他地方保存为HTMLdocument)
In the above code, the location parameter specifies the center point of the map (latitude and longitude of Beijing), and the zoom_start parameter specifies the initial zoom level of the map.
2. Save the map
If you are not running the code in Jupyter Notebook, or want to save the map as an HTML file for viewing elsewhere, you can use the save method:
('beijing_map.html')
3. Add a tag
Adding markers on a map is a very common operation. You can use the Marker class to create markers and add them to the map via the add_to method. Here is a sample code for adding tags:
import folium # Create a mapm = (location=[39.9042, 116.4074], zoom_start=10) # Create a tagmarker = ([39.9042, 116.4074], popup='* Square') # Add tags to the mapmarker.add_to(m) # Save the map('beijing_map_with_marker.html')
In the above code, the popup parameter specifies the text information displayed when the tag is clicked.
3. Advanced functions
1. Add a layer
Folium supports a variety of map layers, such as Google Maps, satellite maps, etc. You can specify different map layers through the tiles parameter. Here is a sample code using Google Maps layers:
import folium # Create a map, use Google Maps layersm = (location=[39.9042, 116.4074], zoom_start=10, tiles='Stamen Toner') # Save the map('beijing_map_with_google_tiles.html')
In addition to Stamen Toner, Folium also supports a variety of other map layers, such as Stamen Terrain, Mapbox Bright, etc.
2. Draw polygons
Folium also supports drawing polygons, which is very useful when displaying geographic areas. You can use the Polygon class to create polygons and add them to the map via the add_to method. Here is a sample code for drawing polygons:
import folium # Create a mapm = (location=[39.9042, 116.4074], zoom_start=10) # Create polygonspolygon = ([[39.9, 116.3, 39.92, 116.4, 39.9, 116.4]]) # Add polygons to the mappolygon.add_to(m) # Save the map('beijing_map_with_polygon.html')
In the above code, the Polygon class accepts a list of coordinate points as a parameter that defines the vertices of the polygon.
3. Add a heat map
Thermogram is a visual way to show data density and spatial distribution. Folium's HeatMap plugin can help you draw heat maps. Here is an example code for drawing a heat map:
import folium from import HeatMap # Create a mapm = (location=[39.9042, 116.4074], zoom_start=10) # Create heat map dataheat_data = [ [39.9, 116.3], [39.91, 116.35], [39.92, 116.4], [39.9, 116.45], [39.89, 116.4] ] # Create a heat map and add it to the mapHeatMap(heat_data).add_to(m) # Save the map('beijing_map_with_heatmap.html')
In the above code, the HeatMap class accepts a list of coordinate points as a parameter that defines the data points of the heatmap.
4. Add Choropleth map
Choropleth map is used to display the distribution of regional data and is often used to display statistical information in different regions. Folium supports drawing Choropleth maps through GeoJSON data. Here is a sample code for drawing a Choropleth map:
import folium import json import requests # Get GeoJSON data (for example, from an API)url = "/codeforamerica/click_that_hood/master/public/data/" geo_data = (url).json() # Create a mapm = (location=[51.5074, -0.1278], zoom_start=10) # Create a Choropleth layer( geo_data=geo_data, name="choropleth", data={'Borough A': 10, 'Borough B': 20}, # Data Example key_on="", fill_color="YlGn", fill_opacity=0.7, line_opacity=0.2, legend_name="Borough Density" ).add_to(m) # Save the map('choropleth_map.html')
In the above code, the Choropleth class takes GeoJSON data, data dictionary, and other parameters to draw the Choropleth map.
IV. Actual cases
1. Case 1: Showcase the main attractions in Beijing
Here is a sample code showing the main attractions in Beijing:
import folium # Create a mapm = (location=[39.9042, 116.4074], zoom_start=10) # Create a tag and add it to the map([39.9042, 116.4074], popup='* Square').add_to(m) ([39.9841, 116.3229], popup='Forbidden City').add_to(m) ([39.9155, 116.3971], popup='Summer Palace').add_to(m) ([39.9848, 116.3255], popup='Bird's Nest').add_to(m) ([39.9049, 116.4060], popup='Water Cube').add_to(m) # Save the map('beijing_map_with_attractions.html')
In the above code, we showcase the main attractions of Beijing by creating multiple Marker objects and specifying their locations and pop-up information.
2. Case 2: Showcase global earthquake data
Below is a sample code showing global seismic data. Suppose you have a CSV file containing seismic data, which contains information such as latitude and longitude of the earthquake, magnitude and other information:
import folium import pandas as pd # Read seismic datadata = pd.read_csv('earthquake_data.csv') # Create a map, set the initial location to a global perspectivem = (location=[0, 0], zoom_start=2) # Function: Determine the color based on the magnitudedef color_by_magnitude(magnitude): if magnitude < 4: return 'green' elif magnitude < 6: return 'orange' else: return 'red' # traverse the data and add circular marks to indicate the earthquake locationfor index, row in (): ( location=[row['Latitude'], row['Longitude']], radius=row['Magnitude'] * 2, # The larger the magnitude, the larger the circle color=color_by_magnitude(row['Magnitude']), fill=True, fill_color=color_by_magnitude(row['Magnitude']), popup=f'Magnitude: {row["Magnitude"]}' ).add_to(m) # Save the map('global_earthquake_map.html')
Case analysis:
- Data preparation: This example assumes that you have a CSV file named earthquake_data.csv, which contains at least three columns Latitude, Longitude, and Magnitude.
- Map initialization: The initial position of the map is set to [0, 0], that is, the intersection of the equator and the prime meridian, and the zoom level is 2 to display the global scope.
- Color mapping: Depending on the magnitude of the earthquake, different colors are represented by green, green represents earthquakes less than magnitude 4, orange represents earthquakes between magnitude 4 and 6, and red represents earthquakes between magnitude 6 and above.
- Marking addition: Use the CircleMarker class to add a circular mark to each earthquake location. The mark size is proportional to the magnitude, the color is determined based on the magnitude mapping, and a pop-up box is set to display magnitude information.
- Save the output: Finally save the map as a global_earthquake_map.html file, which can be opened in the browser to view.
Extended application:
You can further enrich map information, such as adding time dimensions, and displaying dynamic changes in earthquake activity through animations or time series.
Other plug-ins in use, such as TimestampedGeoJson, can create a dynamic time map to visually show the development of earthquakes over time.
Combined with other data sources, such as crustal plate boundary data, more geographical elements can be superimposed on the map to provide a more comprehensive analytical perspective.
5. Skills and best practices
- Performance optimization:
When processing large amounts of data, such as global seismic data, consider using data sampling or aggregation techniques to reduce the number of markers on the map to improve loading speed and interactive performance.
Use grouping to manage different types of markers or layers, so that users can turn on/off display on or off on demand and optimize user experience.
- Custom styles:
Use classes to customize map styles, including marking icons, pop-up frame appearance, etc., to make the map more in line with the project theme or personal preferences.
Select the appropriate map basemap style through the tiles parameter, such as night mode, satellite image, etc., to enhance the map visual effect.
- Enhanced interactiveness:
Adding controls allows users to control the visibility of different layers, especially when including multiple datasets.
Using combined with GeoJSON data, more complex interactive functions can be implemented, such as area click events, attribute query, etc.
- Responsive design:
Make sure the maps are displayed well on different devices and screen sizes, consider resizing and layouting the map with CSS media queries or responsive frameworks.
Use the appropriate width and height parameters to ensure the map is adaptive to the container size.
6. Conclusion
As a map visualization library in Python, Folium has become one of the preferred tools for data scientists and analysts to visualize geospatial data with its ease of use and powerful capabilities. Through the introduction of this article, you not only master the basic usage of Folium, including map creation, marking addition, layer management, etc., but also learn how to use Folium's advanced functions to draw polygons, heat maps, Choropleth maps, etc., and demonstrate Folium's application potential in displaying geographic information and data analysis results through actual cases. In addition, the article provides tips and best practices to help you optimize map performance, enhance interactivity and aesthetics. With in-depth learning and practice of Folium, you will be able to create richer, dynamic and insightful map visualizations that provide strong support for data analysis and decision support.
The above is the detailed information of the operation guide for using Folium to visualize maps in Python. For more information about Python Folium map visualization, please follow my other related articles!