我的目标是制作一张带有旅行路线地图的海报。
您应该能够设置海报尺寸,即图形尺寸。
然后您提供长/纬度点列表。海报是水平还是垂直应取决于脚本,即适合提供的纬度/经度。
然后它应该以 pdf 格式返回海报,放大地图的相关部分,同时仍然填充整个画布。这是我几天来一直在努力解决的最后一部分。我想整个地图的长度需要改变以适应海报尺寸的比例,但我还没有做到。任何建议将非常感激 ! 附言。我知道(bbox_inches='tight'),但它破坏了海报的总尺寸。
示例脚本:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np
# Define the geographic locations (longitude, latitude)
points = np.array([
(18.4241, -33.9249),
(9.5375, 33.8869),
(-16.3151, 28.4682),
(-9.1393, 38.7223),
(-3.7038, 40.4168),
(2.3522, 48.8566),
(10.7522, 59.9139),
])
# Create figure and add a map in Mercator projection
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={'projection': ccrs.Mercator()})
# Calculate bounds
lon_min, lat_min = points.min(axis=0) - 1
lon_max, lat_max = points.max(axis=0) + 1
# Set extent based on points
ax.set_extent([lon_min, lon_max, lat_min, lat_max], crs=ccrs.PlateCarree())
# Plot points
ax.scatter(points[:, 0], points[:, 1], marker='o', color='red', transform=ccrs.Geodetic())
# Add coastlines for reference
ax.coastlines()
# Save the plot as a PDF
plt.savefig("map.pdf")
您可以使用 constrainedlayout 使轴填充图形,并使用 set_adjustable 更新数据限制,以便地图成为扩展轴的正确形状:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np
# Define the geographic locations (longitude, latitude)
points = np.array([
(18.4241, -33.9249),
(9.5375, 33.8869),
(-16.3151, 28.4682),
(-9.1393, 38.7223),
(-3.7038, 40.4168),
(2.3522, 48.8566),
(10.7522, 59.9139),
])
# Create figure and add a map in Mercator projection
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw={'projection': ccrs.Mercator()},
layout='constrained')
# Calculate bounds
lon_min, lat_min = points.min(axis=0) - 1
lon_max, lat_max = points.max(axis=0) + 1
# Set extent based on points
ax.set_extent([lon_min, lon_max, lat_min, lat_max], crs=ccrs.PlateCarree())
# Adjust the data limits so that the map fills the figure without stretching
ax.set_adjustable(adjustable='datalim')
# Plot points
ax.scatter(points[:, 0], points[:, 1], marker='o', color='red', transform=ccrs.Geodetic())
# Add coastlines for reference
ax.coastlines()
# Save the plot as a PDF
plt.savefig("map.png")