VS Code中Matplotlib图表出现水平条重叠异常问题
问题:Matplotlib图表出现水平条重叠异常(VS Code环境)
在VS Code开展Python项目时,近期使用Matplotlib绘制的图表出现异常:图表中出现水平条并与其他图表重叠,不清楚是哪项设置变更导致该问题。
异常图表及对应代码
异常图表1

# creating a visual to see the brands that are most consumed by mainstream - young singles/couple young_mainstream = purchases.loc[purchases['LIFESTAGE'] == 'YOUNG SINGLES/COUPLES'] young_mainstream = young_mainstream.loc[young_mainstream['MEMBER_TYPE'] == 'Mainstream'] ax = young_mainstream['BRAND_NAME'].value_counts().sort_values(ascending = True).plot.barh(figsize = (10, 5)) ax.set_xlabel('Number of packets purchased') ax.set_ylabel('Brand Name') plt.show()
异常图表2

# Plot a histogram to visualise distribution of brand names plt.figure(facecolor = 'w') plt.bar(transactions['BRAND_NAME'], transactions['PROD_QTY']) plt.xlabel('Brand Name') plt.ylabel('Quantity') plt.show()
期望效果(图表1)

已尝试排查动作
- 排查VS Code显示设置,未找到有效解决方向
解决方案建议
- 重置Matplotlib绘图状态:在每次调用
plt.show()前或代码开头添加plt.clf()(清除当前图表)或plt.close('all')(关闭所有图表窗口),避免之前的绘图缓存残留影响当前渲染。 - 指定Matplotlib后端:在代码开头添加后端指定代码,比如:
import matplotlib matplotlib.use('TkAgg') # 也可尝试'Qt5Agg'、'Agg'等后端,根据系统环境调整 import matplotlib.pyplot as plt - 更新依赖库:执行命令升级Matplotlib到最新稳定版,修复可能的版本兼容问题:
pip install --upgrade matplotlib - 检查VS Code Jupyter扩展设置:若使用Jupyter交互式窗口运行代码,在VS Code设置中找到
Jupyter: Interactive Window Renderer,将其设置为svg或canvas,避免渲染引擎导致的异常。
内容的提问来源于stack exchange,提问作者Dishi Gupta
相关产品推荐
相关产品推荐

