python matplotlib.pyplot 官网示例代码出错?

引用https://matplotlib.org/stable/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py中的代码,提示没有bar_label方法!

以下是源代码:

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


labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()

ax.bar_label(rects1, padding=3)  # 问题出现了!!!
ax.bar_label(rects2, padding=3)  # 问题出现了!!!

fig.tight_layout()

plt.show()

更新了matplotlib包,也无济于事,快帮我看看是哪里出了问题???

 

嗯,我也出错了

这个是3.4.1版本才添加的,所以需要安装3.4.1版本的matplotlib,如果:

conda install matplotlib==3.4.1

没有成功,那就使用以下命令来查看可用版本:

anaconda search -t conda matplotlib
conda install -c https://conda.anaconda.org/conda-forge matplotlib==3.4.1

发现可用版本后安装,成功后:

没有再报错,成功解决!

官网代码是基于3.4.1最新版的,用pip install --upgrade matplotlib升级为最新版3.4.1版,即可正常运行。参照相同问题的此帖解决办法:https://ask.csdn.net/questions/7412993

对python有要求