不显示pyplot图例的面颜色

2024-09-28 22:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个等高线图,我想使用一个纯白色背景的图例,这样图例就可以在等高线上阅读。在

我的问题是,当我改变脸色时,什么都不会发生。我也尝试过改变framealpha,但是什么都没有发生。这是一个玩具代码,以及由此产生的图形。如何更改图例的面颜色以使图例在轮廓上可读?在

import numpy as np
import matplotlib.pyplot as plt

# Create data

delta = 0.025
x = np.arange(-1.0, 1.0, delta)
y = np.arange(-1.0, 1.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.exp(-X**2 - Y**3)

# Plot data

fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)

# Create legend.
# Code modified from https://github.com/matplotlib/matplotlib/issues/11134

CS_elem,_ = CS.legend_elements()
ax.legend(CS_elem, ['-X**2 - Y**3'], loc='lower left',facecolor="blue", framealpha=1)

enter image description here


Tags: importdatamatplotlibascreatenppltax
2条回答

根据您的注释,您已将legend.frameon设置为False。默认值为True,以便根据the ^{} file的文档“在背景补丁上绘制图例”。如果没有修补程序,facecolor将无法应用。在

您的代码在matplotlib 2.2.2上运行良好。不过,您可以尝试一下this answer中建议的以下解决方案。在

CS_elem,_ = CS.legend_elements()
leg = ax.legend(CS_elem, ['-X**2 - Y**3'], loc='lower left',
                framealpha=1)
frame = leg.get_frame()
frame.set_facecolor('blue')

enter image description here

相关问题 更多 >