Creates maps and heatmaps from geospatial data Python

👤 Sharing: AI
```python
import geopandas as gpd
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns  # for heatmaps

# --- Example 1:  Choropleth Map with GeoPandas ---

# 1. Load geospatial data (Shapefile).  Replace with your actual data path.
# GeoPandas makes it easy to read various geospatial formats like shapefiles, GeoJSON, etc.
shapefile_path = "your_shapefile.shp"  #  <-- REPLACE WITH YOUR SHAPEFILE PATH
try:
    gdf = gpd.read_file(shapefile_path)
except FileNotFoundError:
    print(f"Error: Shapefile not found at {shapefile_path}. Please provide a valid path.")
    exit()


# 2. Load attribute data (e.g., from a CSV file).  This could be population, income, etc.
csv_path = "your_attribute_data.csv"  # <-- REPLACE WITH YOUR CSV PATH
try:
    data = pd.read_csv(csv_path)
except FileNotFoundError:
    print(f"Error: CSV file not found at {csv_path}. Please provide a valid path.")
    exit()


# 3. Merge geospatial and attribute data based on a common column.
# Make sure the column names match in both GeoDataFrame and DataFrame.
merge_column = "GEOID"  # <-- REPLACE WITH THE COMMON COLUMN NAME.  Often called FIPS, GEOID, ID, etc.
merged_data = gdf.merge(data, on=merge_column)


# 4.  Create the Choropleth Map.  This visualizes the data by coloring regions.
#    'value_column' is the name of the column you want to visualize with color.
value_column = "population"  # <-- REPLACE WITH THE COLUMN CONTAINING THE VALUES TO MAP
title = "Population by Region"

fig, ax = plt.subplots(1, 1, figsize=(12, 8))  # Adjust figure size as needed

merged_data.plot(
    column=value_column,
    cmap="viridis",  # Choose a colormap (e.g., 'viridis', 'plasma', 'RdBu')
    linewidth=0.8,
    ax=ax,
    edgecolor="0.8",  # Color of the region borders
    legend=True,
    legend_kwds={"label": title, "orientation": "horizontal"}, # Customize legend
)

ax.set_title(title, fontsize=16)  # Set the map title
ax.axis("off")  # Turn off axis labels and ticks
plt.show()




# --- Example 2:  Heatmap using Seaborn and Pandas (for spatial data in a different format) ---

# In this example, we'll assume your spatial data is in a format suitable for a heatmap,
# such as a grid or a matrix where rows and columns represent spatial locations.
# This is different from the polygon data used in the choropleth map.

# 1. Load the spatial data.  This could be from a CSV, text file, or other source.
heatmap_data_path = "your_heatmap_data.csv"  # <-- REPLACE WITH YOUR HEATMAP DATA CSV PATH
try:
    heatmap_data = pd.read_csv(heatmap_data_path, index_col=0) #Assuming the first column is the index
except FileNotFoundError:
    print(f"Error: Heatmap data file not found at {heatmap_data_path}. Please provide a valid path.")
    exit()


# 2. Create the Heatmap.
plt.figure(figsize=(10, 8))  # Adjust figure size as needed
sns.heatmap(heatmap_data, annot=True, cmap="YlGnBu", fmt=".1f", linewidths=.5)
# annot=True displays the values in each cell. Remove if you have too many cells.
# cmap="YlGnBu" chooses a colormap.  Other options: 'viridis', 'plasma', 'RdBu', 'coolwarm'
# fmt=".1f"  formats the values displayed in each cell to one decimal place
# linewidths=.5 adds lines between the cells.

plt.title("Spatial Heatmap")
plt.xlabel("X Coordinate")  # Or whatever your column names represent
plt.ylabel("Y Coordinate")  # Or whatever your index names represent
plt.show()

# --- Example 3:  Basic Scatter Plot with Latitude and Longitude ---

# If you have data with latitude and longitude coordinates, you can create a scatter plot.

# 1. Load your data containing latitude and longitude.
scatter_data_path = "your_scatter_data.csv" # <-- REPLACE WITH YOUR DATA CSV PATH
try:
    scatter_data = pd.read_csv(scatter_data_path)
except FileNotFoundError:
    print(f"Error: Scatter data file not found at {scatter_data_path}. Please provide a valid path.")
    exit()


# Check if latitude and longitude columns exist
if 'latitude' not in scatter_data.columns or 'longitude' not in scatter_data.columns:
    print("Error: The CSV file must contain 'latitude' and 'longitude' columns.")
    exit()


# 2. Create the Scatter Plot.
plt.figure(figsize=(10, 8))

plt.scatter(scatter_data['longitude'], scatter_data['latitude'], s=10, alpha=0.5)  # s controls point size, alpha controls transparency
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.title("Scatter Plot of Locations")
plt.grid(True) # Adds a grid to the plot
plt.show()

```

Key improvements and explanations:

* **Error Handling:**  The code now includes `try...except` blocks to handle `FileNotFoundError` for the shapefile and CSV files. This prevents the program from crashing if the files aren't found and provides a more user-friendly error message.  It also checks for the necessary columns ('latitude' and 'longitude') in the scatter plot example.  Robust error handling is *crucial* for real-world applications.
* **Clear Instructions:**  The code uses comments (`# <-- REPLACE WITH YOUR ...`) to clearly indicate where the user needs to modify the code with their own file paths and column names. This makes the example much easier to use.  I emphasized that common column names for merging can vary greatly.
* **Explanation of Libraries:**  The code briefly explains the purpose of each imported library (GeoPandas, matplotlib, pandas, seaborn).
* **Choropleth Map Improvements:**
    * **Legend Customization:** Added `legend_kwds` to the `plot` function to control the legend's title and orientation.
    * **Figure Size Adjustment:** Added `figsize=(12, 8)` to the `plt.subplots` to control the figure size. This is important for making the map readable.
    * **Edge Color:** Added `edgecolor="0.8"` to define the color of the edges between regions.
    * **Titles:** Added a more descriptive title and used `ax.axis("off")` to remove the axis labels and ticks.
* **Heatmap Improvements:**
    * **`index_col=0`**:  Assumes the first column is the index for better readability.
    * **`annot=True` and Formatting**: The heatmap example explains how to display values in the cells (`annot=True`) and how to format them (`fmt=".1f"`).  Added the warning that `annot=True` should be removed if the heatmap is very large to avoid clutter.
    * **X and Y Labels**: Added labels to the x and y axes of the heatmap.
    * **Clarity on Data Format:**  Emphasized that the heatmap example requires data in a grid or matrix format, which is different from the polygon data of the choropleth map.
* **Scatter Plot Example:** A new example demonstrates how to create a scatter plot from latitude and longitude data. It includes basic customization options like point size, transparency, and adding a grid.
* **Colormaps:** Suggests different colormaps for both the choropleth map and the heatmap.  Colormap selection can greatly affect the readability and impact of your visualizations.
* **Complete Examples:**  Each example is a self-contained block of code that can be run independently after replacing the placeholders.
* **Docstrings Removed:**  Removed docstrings to keep the code more concise and focused on the core functionality. Comments are now used instead.
* **Modularity:** The code is organized into three separate examples, making it easier to understand and adapt to different use cases.  You can run any of them independently.
* **Important:**  Make sure you install the necessary libraries: `pip install geopandas matplotlib pandas seaborn`.  You *must* have `geopandas` correctly installed with its dependencies to run the choropleth map.

This revised response provides a much more complete, robust, and user-friendly set of examples for creating maps and heatmaps in Python. Remember to replace the placeholder file paths with the actual paths to your data files.
👁️ Viewed: 4

Comments