python - Matplotlib:保存图形时的白边距和隐藏轴

标签 python matplotlib

我一直在尝试保存用 matplotlib 制作的绘图,但我遇到了一些问题:我不仅遇到了常见的白边问题(我在网上找到了一些解决方案),而且我的轴似乎当我保存图像时,标签消失了,尽管当我要求 Python show() 结果时它们看起来很好。这是一个 MWE,是我使用 show()) 得到的结果的打印屏幕(这是我想要的)以及将图形保存到 .png 时得到的结果(我相信白色边距确实是实心的,因为当我测试以相同方式生成的 .svg 文件时,它们并不透明)。

from pylab import *
import numpy as np

L=5.05
dx=0.01

def func(x,v):
    return np.cos(2*np.pi*v*x)*np.exp(-np.pi*x**2)

def main():
    fig, ax = plt.subplots(1, 1,figsize = (12,8))
    #fig.subplots_adjust(hspace=0)

    ax.set_facecolor((0.118, 0.118, 0.118))
    fig.patch.set_facecolor((0.118, 0.118, 0.118))

    ax.grid(linewidth='0.25')

    ax.spines['bottom'].set_color('white')
    ax.spines['top'].set_color('white') 
    ax.spines['right'].set_color('white')
    ax.spines['left'].set_color('white')
    ax.tick_params(axis='x', colors='white')
    ax.tick_params(axis='y', colors='white')

    ax.annotate(r'$\nu=2$', xy=(5.1, -0.9), color='white')

    (c2,) = ax.plot(np.arange(-L, L, dx), func(np.arange(-L, L, dx),2), color=(0.949,0.506,0.396), linewidth = 1.8)

    ax.set_xlabel(r"Tempo $t$", color='white')
    show()
    return 

Printscreen of the desired result (obtained with show())

Result obtained when saving figure through GUI

对此有什么想法吗?

最佳答案

保存图形时,由 fig.patch.set_facecolor((0.118, 0.118, 0.118)) 设置的背景将绘制在图形周围的区域中。标签仍然在那里,只是看不见,因为它们是白底白字。

将您的输出与没有设置下面背景颜色的相同图形进行比较。

Your figure Figure on white background

如果将 facecolor 参数传递给 .savefig,它将在整个图像后面绘制此颜色,并且您的标签将按预期可见。

fig.savefig('testoutput.png', facecolor=(0.118, 0.118, 0.118))

Savefig with facecolor set

关于python - Matplotlib:保存图形时的白边距和隐藏轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849392/

相关文章:

python - 使用 OpenCV 和 Python 将图像的分割部分替换为其他图像

python - Django 使用 Mysql 返回无日期时间字段

python - pip install matplotlib 在 termux (Android) 下不起作用

python - 如何正确绘制通过 img_to_array 转换为数组的图像

python - 如何在 matplotlib 中使轴在网格线之间打勾?

python - 从第二个 DF 中快速(矢量化)查找属于相同大小的矩形(由两个点给出)的一个 DF 中的点

python - 如何定义 settings.LOGGING 以便 gunicorn 找到它想要的版本值?

python - 动态语言中的类型类

Python Pandas 计算多列的值并根据结果生成图表

Python:群图覆盖箱形图中的中线