import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Point, LineString, Polygon
# Create sample geometries
points = [Point(.5, .5), Point(1.5, 1.5), Point(2.5, 2.5), Point(3.5, 3.5), Point(5, 5)]
lines = [LineString([(5, 0), (5, 4), (2, 4)]), LineString([(0, 0), (1, 2), (1.5, 2)])]
polygons = [Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]), Polygon([(2, 2), (3, 2), (3, 3.5), (2, 3)])]
# Create a GeoDataFrame
gdf = gpd.GeoDataFrame({'geometry': points + lines + polygons})
# Separate GeoDataFrame by geometry type
points_gdf = gdf[gdf.geometry.type == 'Point']
lines_gdf = gdf[gdf.geometry.type.isin(['LineString', 'MultiLineString'])]
polygons_gdf = gdf[gdf.geometry.type.isin(['Polygon', 'MultiPolygon'])]
# Plot each geometry type with different styles
fig, ax = plt.subplots()
# The last one is the top layer
# The layer overlaps one by one
polygons_gdf.plot(ax=ax, color='blue', edgecolor='black', alpha=0.5, label='Polygons')
lines_gdf.plot(ax=ax, color='green', linewidth=2, label='Lines')
points_gdf.plot(ax=ax, color='red', markersize=25, label='Points')
# Customize the plot
ax.set_title('GeoDataFrame with Multiple Geometries')
ax.legend()
plt.show()
In this example:
- We create multiple points, lines, and polygons.
- We combine them into a single GeoDataFrame.
- We then separate the GeoDataFrame into different geometry types.
- Finally, we plot each geometry type with different styles and add a legend to distinguish them.
plt.subplots
is a convenient way to create a figure and a set of subplots in Matplotlib. It returns a tuple containing a figure and an array of axes objects. Here’s a basic example to illustrate how it works:
import matplotlib.pyplot as plt
# Create a figure and a set of subplots
fig, ax = plt.subplots()
# Plot data on the axes
ax.plot([1, 2, 3, 4], [10, 20, 25, 30])
# Customize the plot
ax.set_title('Simple Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
# Show the plot
plt.show()
Creating Multiple Subplots
You can also create multiple subplots in a grid layout. For example, to create a 2x2 grid of subplots:
import matplotlib.pyplot as plt
# Create a 2x2 grid of subplots
fig, axs = plt.subplots(2, 2)
# Plot data on each subplot
axs[0, 0].plot([1, 2, 3, 4], [10, 20, 25, 30])
axs[0, 0].set_title('Plot 1')
axs[0, 1].plot([1, 2, 3, 4], [30, 25, 20, 10])
axs[0, 1].set_title('Plot 2')
axs[1, 0].plot([1, 2, 3, 4], [15, 18, 22, 27])
axs[1, 0].set_title('Plot 3')
axs[1, 1].plot([1, 2, 3, 4], [5, 15, 10, 20])
axs[1, 1].set_title('Plot 4')
# Adjust layout to prevent overlap
plt.tight_layout()
# Show the plot
plt.show()
Customizing Subplots
You can customize each subplot individually by accessing the corresponding axes object. For example, you can set titles, labels, and other properties for each subplot.
Would you like to see more specific examples or details on customizing subplots?
标签:plot,set,GeoDataFrame,1061,subplots,plt,gdf,ax,Plotting From: https://www.cnblogs.com/alex-bn-lee/p/18409582