绘制多组带标注堆叠柱状图时出现条形间隙与刻度标签不匹配错误如何解决
问题根因
- 报错
The number of FixedLocator locations (11)...:plt.hist()返回的bins数组长度为「分桶数+1」,你共有10个不同国家,所以bins数组有11个值,但是你传入的x轴标签只有10个国家名称,数量不匹配触发报错。 - 条形之间出现间隙:你使用面向数值型数据的直方图工具绘制离散分类变量的堆叠柱状图,matplotlib对分类变量到坐标的映射逻辑不适配该场景,就会出现多余间隙。
优化后可运行代码
更推荐先做分组统计,直接用pandas的堆叠柱状图接口实现需求,逻辑更清晰也不会出现上述问题:
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 加载数据,可替换为本地csv路径,也可直接用题目提供的测试数据构造DataFrame df = pd.read_csv("C:/Usersjosep/Desktop/Libro1.csv") # 统计每个国家各类型奖牌数量 df_count = df.groupby(['countries', 'type']).size().unstack(fill_value=0) # 调整奖牌顺序匹配颜色:bronze、silver、gold df_count = df_count[['bronze', 'silver', 'gold']] # 绘制堆叠柱状图 plt.figure(figsize=(10,10), dpi= 100) colors= ("#CD7F32","silver","gold") df_count.plot.bar(stacked=True, color=colors, ax=plt.gca()) # 装饰设置 plt.legend(["bronze", "silver","gold"], loc="upper right") plt.title("Histogram of medals achieved by countries colored by type in Tokyo 2020", fontsize=18) plt.text(0, 128, "138") # 对应美国的总奖牌数标注,调整x坐标到第一个国家位置 plt.xlabel("countries") plt.ylabel("amount of medals by type") plt.ylim(0, 130) plt.xticks(rotation=90, horizontalalignment='left') plt.tight_layout() # 自动调整布局避免x轴标签被截断 plt.show()
内容的提问来源于stack exchange,提问作者Jose Antonio Piedehierro Arias
相关产品推荐
相关产品推荐

