matplotlib 如何为保存的图形设置图的面色

kmynzznz  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(123)

我正在使用Docker上使用matplotlib v.3.1.2的代码(我无法更改此),我不知道如何将我保存的图的背景颜色设置为不同于白色的颜色(同时保持fig背景白色)。
在寻找解决方案时,我发现了三种不同的方法,但都不起作用。
方法1(将figaxis的背景色更改为 Azure ):

import matplotlib.pyplot as plt

fig, axis = plt.subplots(nrows=2, ncols=1, facecolor='azure')
for ax in axis:
    ...

...

plt.savefig(..., facecolor=fig.get_facecolor(), transparent=True)

方法2(不做任何事情,即figaxis的背景色保持白色):

import matplotlib.pyplot as plt

fig, axis = plt.subplots(nrows=2, ncols=1)
for ax in axis:
    ...
    ax.set_facecolor('azure')

...

plt.savefig(..., facecolor=fig.get_facecolor(), transparent=True)

方法3(结果与方法2相同):

import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'azure'

fig, axis = plt.subplots(nrows=2, ncols=1)
for ax in axis:
    ...

...

plt.savefig(..., facecolor=fig.get_facecolor(), transparent=True)

我做错了什么?

下面是完整的测试示例

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

plt.rcParams['font.serif'] = 'Rockwell'
plt.rcParams['font.family'] = 'serif'

BACKGROUND_COLOR = (1, 1, 1)
FONT_COLOR = (0.1, 0.1, 0.1)
MY_PATH = ...

fig, axes = plt.subplots(nrows=2, ncols=1)

vals = [[random.uniform(1.0, 8.0) for i in range(10)], 
        [random.uniform(1.0, 8.0) for i in range(10)]]
x = [i for i in range(10)]

colors = ['#F15854', '#B276B2']
legends = ['Feature 1', 'Feature 2']
for (colr, leg, y) in zip(colors, legends, vals):
    for i in [0, 1]:
        axes[i].plot(x, y, label=leg, linewidth=2, color=colr, alpha=1)

frm_min = int(x[0])
frm_max = int(x[-1])
for ax in axes:
    range_x = np.arange(frm_min, frm_max + 1, 2)
    ax.set_xticks(range_x)
    ax.set_xticklabels(range_x, fontsize=10)
    range_y = range(0, 8, 1)
    ax.set_yticks(range_y)
    ax.set_yticklabels(range_y, fontsize=10)
    ax.set_xlim(frm_min, frm_max)
    ax.grid(which='major', axis='x', linestyle=':')
    ax.set_xlabel('Time (s)')
    ax.set_ylabel('Value')

    main_legend = ax.legend(loc=7, ncol=1, borderaxespad=-10.0, fontsize=16)
    main_frame = main_legend.get_frame()
    main_frame.set_facecolor(BACKGROUND_COLOR)
    main_frame.set_edgecolor(BACKGROUND_COLOR)
    for text in main_legend.get_texts():
        text.set_color(FONT_COLOR)

    ax.set_facecolor('azure')

fig.suptitle('Figure title', fontsize=24, ha='center', color=FONT_COLOR)
fig.tight_layout(rect=[0, 0, 0.925, 0.925])  

plt.show()
plt.savefig(
    os.path.join(MY_PATH, 'filename.png'),
    bbox_inches='tight',
    dpi=300,
    facecolor=fig.get_facecolor(),
    transparent=True,
)
plt.close(fig)
8e2ybdfx

8e2ybdfx1#

解决办法其实很简单:我不得不将savefig()中的transparent更改为False。现在,我在最初的文章中描述的所有三种方法都按照他们预期的那样做了。结案了!

相关问题