matplotlib调用savefig保存png文件时坐标轴及标题丢失如何解决
问题解决方法
这个问题通常由两个原因导致:一是布局裁剪导致坐标轴元素被切掉,二是png透明背景下坐标轴元素颜色和背景重合,你可以按以下步骤修改代码:
1. 先调整布局避免元素裁剪
在所有绘图逻辑完成后、执行保存前,先调用plt.tight_layout()自动调整所有元素的位置,避免被画布边缘裁剪。
2. 显式指定坐标轴元素颜色(针对透明png)
保存带透明背景的png时,如果你的绘图环境默认将坐标轴、文字设为白色,透明背景下在浅色预览界面中会无法看到白色元素,可显式设置所有文字和坐标轴为黑色。
3. 非透明png指定白底和jpg配置对齐
jpg保存时默认使用白色背景,存非透明png时显式指定facecolor='white'即可和jpg保存效果完全一致。
修改后的完整代码
import matplotlib.pyplot as plt import pandas as pd # 这里假设你的df、col、x、y、track变量已经提前定义好 # creating a scatter plot fig = df.plot(kind='scatter', x='sentimentscore', y='sentimentmagnitude', c = col) plt.axvline(0, 0, 10, color = "grey") # creating vertical dividing line plt.xlabel('Sentiment score') plt.ylabel('Sentiment magnitude') plt.title('Sentiment analysis') fig.set_ylim([3, 15]) # annotating points with track numbers for i in range(len(x)): plt.annotate(track[i], (x[i] - 0.002, y[i] + 0.25)) # 新增:显式设置所有坐标轴元素为黑色 ax = plt.gca() ax.spines[:].set_color('black') ax.tick_params(axis='both', colors='black') ax.xaxis.label.set_color('black') ax.yaxis.label.set_color('black') ax.title.set_color('black') # 新增:自动调整布局 plt.tight_layout() # 保存时新增facecolor参数(非透明png用) fig.figure.savefig("graph1.png", bbox_inches='tight', dpi=200, facecolor='white') # 透明png保留transparent参数即可 fig.figure.savefig("transparentgraph1.png", transparent=True, bbox_inches='tight', dpi=200)
内容的提问来源于stack exchange,提问作者user16096708
相关产品推荐
相关产品推荐

