Python直方图报错(TypeError)且无图例问题的修复方法求助
问题分析与解决
错误原因
你踩了两个关键坑:
plt.hist()参数用错了:plt.bar()返回的是图形元素(BarContainer,包含多个Rectangle对象),但plt.hist()需要的是数值数组来绘制数据分布。把图形对象传给hist,它会试图比较这些对象,直接触发TypeError。- 绘图逻辑混淆:你同时调用
bar和hist,相当于在同一张图上叠加两种完全不同的图表,错误的hist调用还会干扰图例的识别。
修正代码(分组柱状图场景)
如果你要的是对比两组数据的分组柱状图,直接去掉错误的plt.hist()调用即可:
import matplotlib.pyplot as plt import numpy as np # 替换成你的实际数据即可 ind = np.arange(5) # 类别数量 width = 0.35 no_no_show_prop = [0.2, 0.4, 0.6, 0.8, 0.3] # 到场比例数据 yes_no_show_prop = [0.8, 0.6, 0.4, 0.2, 0.7] # 未到场比例数据 plt.style.use('seaborn-deep') # 绘制两组分组柱状图 plt.bar(ind, no_no_show_prop, width, alpha=.7, label='Showed up') plt.bar(ind + width, yes_no_show_prop, width, alpha=.7, label='Did not show') # 设置图例和x轴标签(可选但让图表更清晰) plt.legend(loc='upper right') plt.xticks(ind + width/2, ['类别1', '类别2', '类别3', '类别4', '类别5']) plt.show()
如果需要同时画柱状图和直方图
如果你的需求是同时展示比例的柱状图和原始数据的直方图,建议用子图分开绘制,避免图表混乱:
import matplotlib.pyplot as plt import numpy as np # 示例数据 ind = np.arange(5) width = 0.35 no_no_show_prop = [0.2, 0.4, 0.6, 0.8, 0.3] yes_no_show_prop = [0.8, 0.6, 0.4, 0.2, 0.7] # 用于直方图的原始数值数据 no_show_raw = np.random.rand(100) * 10 yes_show_raw = np.random.rand(100) * 10 plt.style.use('seaborn-deep') # 创建1行2列的子图布局 fig, (ax_bar, ax_hist) = plt.subplots(1, 2, figsize=(12, 5)) # 子图1:分组柱状图 ax_bar.bar(ind, no_no_show_prop, width, alpha=.7, label='Showed up') ax_bar.bar(ind + width, yes_no_show_prop, width, alpha=.7, label='Did not show') ax_bar.legend() ax_bar.set_title('Attendance Proportion') ax_bar.set_xticks(ind + width/2) ax_bar.set_xticklabels(['类别1', '类别2', '类别3', '类别4', '类别5']) # 子图2:直方图 bins = np.linspace(0, 10, 30) ax_hist.hist([no_show_raw, yes_show_raw], bins, alpha=.7, label=['Showed up', 'Did not show']) ax_hist.legend() ax_hist.set_title('Raw Data Distribution') plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Aaliyah Motala
相关产品推荐
相关产品推荐

