Skip to main content
 首页 » 编程设计

python之matplotlib.legend.set_zorder() 在 ipython 笔记本中不起作用

2025年05月04日14leader

这是一件让我非常恼火的事情。我已按照 strange matplotlib zorder behavior with legend and errorbar 中的指示进行操作但它不起作用。这是一个非常简短的工作示例

x = np.linspace(0,10)  
y = (x-5)**2  
plt.plot(x,y,label='test curve',zorder=100) 
plt.legend(loc='center right').set_zorder(102) 

如果您尝试这样做,您会发现图例仍在曲线下方,尽管使用了 zordering。有谁知道为什么吗?

我在 ipython 3.1.0 上使用 matplotlib 1.3.1

请您参考如下方法:

根据@cel 的评论,我同意您需要为图例添加不透明背景。尝试添加:

leg=plt.legend(loc='center right') 
leg.set_zorder(102) 
leg.get_frame().set_facecolor('w') 

也可以在 matplotlibrc 或通过 plt.rcParams 设置 legend.facecolor


或者确保图例框架的 fill 设置为 True:

print leg.get_frame().get_fill() 

如果打印出False,试试

leg.get_frame().set_fill(True)