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

Matplotlib绘图:如何将地区名称设为X轴标签

Fix: Display Region Names as X-axis Labels in Matplotlib Bar Chart

我来帮你搞定这个问题!问题的根源在于你传递给plt.xticks()的参数:location_withmax_no_of_companies是一个pandas Series对象,当你直接把它作为标签参数传入时,matplotlib会默认读取Series的数值(企业数量),而不是我们需要的索引(地区名称)。

解决方案1:手动指定X轴标签为Series的索引

修改plt.xticks()的第二个参数,明确传入Series的index属性(也就是地区名称),同时可以添加旋转参数避免标签重叠:

import numpy as np
import matplotlib.pyplot as plt

# 保留你的分组和排序逻辑
location_group = fortune_df.groupby('Location')
location_withmax_no_of_companies = location_group.size().sort_values(ascending=False)[:10]

lpos = np.arange(10)
# 关键修改:传入index作为X轴标签,添加rotation让标签倾斜显示
plt.xticks(lpos, location_withmax_no_of_companies.index, rotation=45)
plt.bar(lpos, location_withmax_no_of_companies)

# 可选:添加坐标轴标题和图表标题
plt.xlabel('Region')
plt.ylabel('Number of Companies')
plt.title('Top 10 Regions by Number of Fortune Companies')

# 自动调整布局,防止标签被截断
plt.tight_layout()
plt.show()

解决方案2:使用Pandas自带的绘图方法(更简洁)

Pandas的Series对象内置了绘图功能,会自动将索引作为X轴标签,无需手动处理坐标轴位置,代码更简洁不易出错:

import matplotlib.pyplot as plt

# 保留你的分组和排序逻辑
location_group = fortune_df.groupby('Location')
location_withmax_no_of_companies = location_group.size().sort_values(ascending=False)[:10]

# 直接调用plot.bar(),rot参数控制标签旋转角度
location_withmax_no_of_companies.plot(kind='bar', rot=45)

# 添加必要的标注
plt.xlabel('Region')
plt.ylabel('Number of Companies')
plt.title('Top 10 Regions by Number of Fortune Companies')

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:41:49