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

如何修正matplotlib代码基于DataFrame绘制条形图

错误原因
  • plt.plot()是matplotlib原生折线绘制接口,本身不存在kind参数,末尾追加plt.plot(kind ='bar')属于无效写法,kind是pandas封装的绘图方法的参数,不能直接在matplotlib原生接口中调用。
  • 坐标轴标签颠倒本质是横纵轴字段映射逻辑错误,目标要求y轴为年份、x轴为人口,属于横向条形图场景,直接复用折线图的轴配置会导致字段对应关系错乱。
正确实现代码

首先确认你的DataFrame包含三个核心字段:ID Year(年份值)、Hispanic or Latino(对应族群人口数)、Not Hispanic or Latino(对应族群人口数),每行对应单一年份的两类族群统计值。
实现横向分组条形图的可运行代码如下:

import matplotlib.pyplot as plt
import pandas as pd

# 替换为你实际使用的DataFrame,以下为样例数据
df = pd.DataFrame({
    "ID Year": [2010, 2015, 2020],
    "Hispanic or Latino": [50500000, 56600000, 62100000],
    "Not Hispanic or Latino": [258000000, 262000000, 269000000]
})

bar_h = 0.35  # 单条横向柱的高度
y_index = range(len(df["ID Year"]))  # 生成y轴位置索引

# 绘制两组横向柱,设置y轴偏移避免同一年份的柱体重叠
plt.barh([i - bar_h/2 for i in y_index],
         df["Hispanic or Latino"],
         height=bar_h,
         label="Hispanic or Latino")
plt.barh([i + bar_h/2 for i in y_index],
         df["Not Hispanic or Latino"],
         height=bar_h,
         label="Not Hispanic or Latino")

# 显式配置坐标轴,避免标签颠倒
plt.yticks(y_index, df["ID Year"])
plt.xlabel("TOT Population")
plt.ylabel("ID Year")

# 添加图例、自动调整布局防止标签截断
plt.legend()
plt.tight_layout()
plt.show()
补充说明
  • 如果你习惯用pandas封装的绘图接口,可以直接用df.plot(kind='barh', y=['Hispanic or Latino', 'Not Hispanic or Latino'], x='ID Year')实现相同效果,不需要额外嵌套plt.plot()调用。
  • 只要显式指定x、y轴对应的字段和标签,就不会出现坐标轴颠倒的问题,不要直接复用折线图阶段的轴配置参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 10:01:28