如何在 matplotlib 中设置绘图的外部背景颜色

Col*_*ole 3 python matplotlib

问候,

我想在 matplotlib 中更改绘图的外部颜色。我可以找到许多关于如何更改内部 bg 颜色但外部 bg 颜色拒绝更改的示例。

图像的白色部分是我所说的“外部”背景。最外面的颜色只是为了对比白色,所以它不会与堆栈溢出背景混合,也不是绘图/图表的一部分。

图表

我试过用set_facecolor()它来改变它,但它不起作用。

# Setting up data
x = list(history['daily'].keys())[-30*months:]
x_av = list(history['average'].keys())[-30*months:]
y = list(history['daily'].values())[-30*months:]
y_av = list(history['average'].values())[-30*months:]

# Setting up figure
fig = pyplot.figure()
fig.set_figheight(6)
fig.set_figwidth(12)

# Formatting figure
fig.patch.set_antialiased(True)

# Setting up axis
ax = fig.add_subplot(111, axisbg='#2e3136')
ax.plot(x, y, '#e1bb34', x_av, y_av, '#b2dbee')

# Formatting axis
ax.get_yaxis().grid(color='#3e4146', linestyle='-')
ax.get_xaxis().grid(color='#3e4146', linestyle='-')

ax.spines['bottom'].set_color('#1e2124')
ax.spines['top'].set_color('#1e2124')
ax.spines['left'].set_color('#1e2124')
ax.spines['right'].set_color('#1e2124')

ax.get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda _y, p: '{:,}'.format(_y)))
ax.get_xaxis().set_major_formatter(ticker.FuncFormatter(lambda _x, p: datetime.fromtimestamp(_x/1000.0).strftime('%b %d')))

[i.set_color('white') for i in pyplot.gca().get_xticklabels()]
[i.set_color('white') for i in pyplot.gca().get_yticklabels()]

buf = BytesIO()
fig.savefig(buf, format='png', bbox_inches='tight')
pyplot.close()
buf.seek(0)
Run Code Online (Sandbox Code Playgroud)

Log*_*ers 6

您应该能够将facecolorkwarg设置为savefig,这将确保在写入图像时设置它。

fig.savefig(buf, format='png', bbox_inches='tight', facecolor='#2e3136')
Run Code Online (Sandbox Code Playgroud)

要从轴拉出颜色:

fig.savefig(buf, format='png', bbox_inches='tight', facecolor=ax.get_axis_bgcolor())
Run Code Online (Sandbox Code Playgroud)