Matplotlib直方图添加标签、正态分布及bar_label报错问题求助
直方图数据标签与正态分布曲线添加解决方案
1. 解决AttributeError: module 'matplotlib.pyplot' has no attribute 'bar_label'错误
这个问题根源是你的matplotlib版本低于3.4.0——plt.bar_label是3.4.0版本才新增的函数,低版本不支持。给两种解决办法:
办法一:升级matplotlib
如果是Jupyter环境,直接在代码块里执行升级命令:
!pip install --upgrade matplotlib
本地环境的话,在终端执行pip install --upgrade matplotlib即可。
办法二:手动给条形加标签(兼容低版本)
不想升级的话,直接遍历每个条形,用plt.text手动写标签,效果和bar_label一致:
def make_plot(): plt.figure(figsize=(8, 6)) values, bins, bars = plt.hist(t0wordcloudtext_df['afinn_adjusted'], bins=15, edgecolor='white') # 手动添加标签,替代plt.bar_label for bar, val in zip(bars, values): height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2., height, f'{int(val)}', # 要显示小数就改成f'{val:.1f}' ha='center', va='bottom', fontsize=20, color='navy') plt.margins(x=0.01, y=0.1) plt.ylabel('Frequency') plt.xlabel('Adjusted AFINN') plt.title('t0 AFINN sentiment analysis ') plt.grid(True) plt.show()
2. 叠加正态分布曲线
在直方图上添加正态分布曲线,需要先计算数据的均值、标准差,再生成对应曲线数据:
import numpy as np import matplotlib.pyplot as plt def make_plot(): plt.figure(figsize=(8, 6)) # 先剔除缺失值,避免计算出错 data = t0wordcloudtext_df['afinn_adjusted'].dropna() values, bins, bars = plt.hist(data, bins=15, edgecolor='white', color='salmon') # 手动加标签 for bar, val in zip(bars, values): height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2., height, f'{int(val)}', ha='center', va='bottom', fontsize=20, color='navy') # 计算正态分布参数 mu = data.mean() sigma = data.std() # 生成曲线的x、y值,要把密度值转成和直方图频率匹配的刻度 x = np.linspace(bins.min(), bins.max(), 100) y = (1/(sigma * np.sqrt(2 * np.pi))) * np.exp(-(x - mu)**2 / (2 * sigma**2)) y_scaled = y * len(data) * (bins[1] - bins[0]) # 绘制正态曲线 plt.plot(x, y_scaled, 'darkblue', linewidth=2, label='正态分布曲线') plt.legend() plt.margins(x=0.01, y=0.1) plt.ylabel('Frequency') plt.xlabel('Adjusted AFINN') plt.title('t0 AFINN sentiment analysis ') plt.grid(True) plt.savefig('/content/t0_afinn_hist.png') plt.show()
3. 保留pandas绘图方式加标签
如果想继续用df.plot(kind='hist')而不是plt.hist,同样可以手动获取条形对象加标签:
def make_plot(): plt.figure(figsize=(8, 6)) ax = df_vaderized['vader_compound'].plot(kind='hist', bins=15, color='thistle') plt.ylabel('Frequency') plt.title('t0 sentiment analysis') plt.grid(True) # 获取所有条形并添加标签 bars = ax.patches for bar in bars: height = bar.get_height() ax.text(bar.get_x() + bar.get_width()/2., height, f'{int(height)}', ha='center', va='bottom', fontsize=12) plt.savefig('/content/t0_5.png') plt.show()
内容的提问来源于stack exchange,提问作者Stuart M
相关产品推荐
相关产品推荐

