Python绘制2021-2022年月度销量柱状图遇ModuleNotFoundError求助
解决ModuleNotFoundError: No module named 'matplotlib'错误
你遇到的错误是因为当前Python环境未安装matplotlib库,按对应环境的命令安装即可:
安装命令
- 全局Python环境(使用pip):
pip install matplotlib - 区分Python3环境(使用pip3):
pip3 install matplotlib - Anaconda/Miniconda环境:
conda install matplotlib
注意事项
安装完成后,需确认代码运行环境与安装matplotlib的环境一致——比如使用VS Code、PyCharm等IDE时,要在设置中选择对应的Python解释器。
你的代码逻辑正确,安装好依赖后就能生成2021、2022年上半年各月份销量的对比柱状图,已将原代码中的葡萄牙语内容翻译为中文,代码如下:
import matplotlib.pyplot as plt import numpy as np meses = ['一月', '二月', '三月', '四月', '五月', '六月'] vendas_2021 = [150, 200, 220, 210, 240, 230] vendas_2022 = [180, 210, 235, 205, 250, 245] x = np.arange(len(meses)) largura = 0.35 fig, ax = plt.subplots() rects1 = ax.bar(x - largura/2, vendas_2021, largura, label='2021', color='blue') rects2 = ax.bar(x + largura/2, vendas_2022, largura, label='2022', color='green') ax.set_xlabel('月份') ax.set_ylabel('销量') ax.set_title('2021和2022年各月份销量对比') ax.set_xticks(x) ax.set_xticklabels(meses) ax.legend() def autolabel(rects): for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) plt.show()
内容的提问来源于stack exchange,提问作者Gael
相关产品推荐
相关产品推荐

