You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Geopandas绘制美国地图:如何修改图表背景颜色?

解决方案

你之前的代码存在几个关键问题,调整后就能实现黑色画布背景:

  1. 未绑定Matplotlib的Axes对象:Geopandas的plot()需要指定ax参数,将地图绘制到你创建的子图上,这样才能通过Axes对象修改背景。
  2. 参数使用错误:原代码里的set_facecolor不是plot()的合法参数,应该通过Axes对象的set_facecolor()方法设置背景色。
  3. 未适配黑色背景的文字样式:黑色背景下,标题、刻度、图例文字需要改成浅色才能看清,否则会被背景淹没。

正确代码示例:

import geopandas as gpd
import matplotlib.pyplot as plt

# 读取并预处理地图数据
us_map = gpd.read_file('tl_2020_us_state.shp')
exclude_states = ['Alaska', 'Hawaii', 'United States Virgin Islands', 'Commonwealth of the Northern Mariana Islands', 'Guam', 'American Samoa', 'Puerto Rico']
updated_us_map = us_map.loc[~us_map['NAME'].isin(exclude_states)]

# 统计各州地点数量并合并数据
state_occurrences = us_only_places_df['State'].value_counts().reset_index().rename(columns={'index':'NAME','State':'count'})
merge_map = updated_us_map.merge(state_occurrences, on='NAME')

# 创建画布和子图,设置黑色背景
fig, ax = plt.subplots(figsize=(15,20))
ax.set_facecolor('black')  # 设置画布背景为黑色

# 绘制地图,绑定到指定子图
merge_map.plot(
    ax=ax,
    column='count',
    cmap='Oranges',
    legend=True,
    legend_kwds={
        'label': "地点数量",
        'orientation': "vertical",
        'shrink': 0.4,
        'facecolor': 'black',  # 图例背景设为黑色
        'labelcolor': 'white',  # 图例文字设为白色
        'tick_params': {'colors': 'white'}  # 图例刻度文字设为白色
    },
    edgecolor='white',  # 州边界改为白色,适配黑色背景
    figsize=(15,20)
)

# 设置标题和刻度样式
plt.title('美国各州保存地点数量统计', color='white', fontsize=16)
ax.tick_params(axis='both', colors='white')  # 坐标轴刻度文字设为白色

plt.show()

核心调整点:

  • 通过fig, ax = plt.subplots()创建子图对象,调用ax.set_facecolor('black')直接设置画布背景。
  • 调用merge_map.plot()时传入ax=ax,确保地图绘制在已设置背景的子图上。
  • 同步修改图例、标题、刻度的颜色,保证在黑色背景下的可读性。
  • 将州边界颜色改为白色,强化地图轮廓的视觉对比。

内容的提问来源于stack exchange,提问作者TechNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:53:16