如何编写for循环为预分箱DataFrame各列按团队索引分组绘制直方图
问题解决方法
报错原因
matplotlib库的ax.hist()方法本身不支持by参数,该参数是Pandas内置绘图接口的专属参数,传入不存在的参数就会触发你遇到的AttributeError。
另外补充:你的数据已经完成了分箱和数值统计,不需要再调用hist接口,直接用柱状图bar()绘制更简单,避免使用weights参数带来的额外复杂度。
可直接运行的实现代码
import pandas as pd import matplotlib.pyplot as plt # 预处理数据,固定bin的显示顺序,避免自动排序错乱 df = df.reset_index() df['bin_str'] = df['bin'].astype(str) bin_order = df['bin_str'].unique().tolist() # 拿到所有团队标识和待绘制的数值列 team_list = df['name'].unique().tolist() value_cols = ['time_spent_inx', 'time_spent_iny'] # 批量绘图:每个团队+每列数据单独生成一张图 for team in team_list: # 筛选当前团队的数据,按预设分箱顺序重排 team_df = df[df['name'] == team].set_index('bin_str').reindex(bin_order) for col in value_cols: fig, ax = plt.subplots(figsize=(10, 6)) # 直接绘制柱状图,无需用hist做二次分箱 ax.bar(x=team_df.index, height=team_df[col]) # 配置轴样式 ax.set_title(f'{team} - {col}分布', fontsize=15) ax.set_xticklabels(team_df.index, rotation=90, fontsize=12) ax.tick_params(axis='y', labelsize=12) plt.tight_layout() # 若需要保存到本地可取消下方注释 # plt.savefig(f'{team}_{col}.png', dpi=150) plt.show()
若坚持使用hist接口实现
如果一定要用hist方法绘制,去掉错误的by参数,循环遍历分组单独绘制即可,参考代码如下:
df = df.reset_index() df['bin_str'] = df['bin'].astype(str) bin_order = df['bin_str'].unique().tolist() team_list = df['name'].unique().tolist() value_cols = ['time_spent_inx', 'time_spent_iny'] for team in team_list: team_df = df[df['name'] == team] for col in value_cols: fig, ax = plt.subplots(figsize=(10,6)) ax.hist(team_df['bin_str'], bins=len(bin_order), weights=team_df[col]) ax.set_title(f'{team} - {col}分布', fontsize=15) ax.set_xticklabels(bin_order, rotation=90, fontsize=12) ax.tick_params(axis='y', labelsize=12) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

