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

Matplotlib绘制三类评分柱状图:TV Series缺失1、2分显示0%的问题

解决评分分布柱状图缺失0%显示的问题

直接手动补缺失项太麻烦,用pandas的reindex方法就能自动补全缺失的评分索引并填充0,完美解决shape不匹配的问题,同时让x轴1、2分位置显示0%。

关键修改步骤

把生成三个评分百分比的代码替换成下面的写法,用reindex指定完整的1-10分索引,缺失项填充0:

x_axis = np.arange(1,11)
# 用reindex补全缺失的评分项,填充0
movies_x = movies['your rating'].value_counts(normalize=True).sort_index().reindex(x_axis, fill_value=0)*100
tvseries_x = tvseries['your rating'].value_counts(normalize=True).sort_index().reindex(x_axis, fill_value=0)*100
tveps_x = tveps['your rating'].value_counts(normalize=True).sort_index().reindex(x_axis, fill_value=0)*100

修改后的完整代码

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

fig, ax = plt.subplots(figsize=(10,4))
x_axis = np.arange(1,11)

# 核心修改:用reindex补全1-10所有评分项,缺失的填0
movies_x = movies['your rating'].value_counts(normalize=True).sort_index().reindex(x_axis, fill_value=0)*100
tvseries_x = tvseries['your rating'].value_counts(normalize=True).sort_index().reindex(x_axis, fill_value=0)*100
tveps_x = tveps['your rating'].value_counts(normalize=True).sort_index().reindex(x_axis, fill_value=0)*100

width = 0.3
# 现在三个数据都对应完整的x_axis,不用再切片x_axis[2:]了
ax.bar(x_axis-width, movies_x, width, label = 'Movies')
ax.bar(x_axis, tveps_x, width, label = 'Episodes')
ax.bar(x_axis+width, tvseries_x, width, label = 'Series')

ax.bar_label(ax.containers[0], color='blue', fmt='%.f%%', fontsize=8)
ax.bar_label(ax.containers[1], color='red', fmt='%.f%%', fontsize=8)
ax.bar_label(ax.containers[2], color='green', fmt='%.f%%', fontsize=8)

ax.set_xticks(x_axis)
ax.set_xlabel('Rating')
ax.set_ylabel('Percent')
ax.set_title('Rating Distribution per rating type')
ax.legend(loc=6)
plt.tight_layout()
plt.show()

原理说明

  • reindex(x_axis, fill_value=0)会强制让Series的索引变成1到10,原来没有的1、2分位置会自动填充0,这样三个Series的长度都是10,和x_axis完全匹配,不会再报shape mismatch错误。
  • 绘图时直接用完整的x_axis+width绘制TV Series,x轴1、2分位置就会显示0%的柱子,满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:11:38