Matplotlib:使用 twinx 时在图例上绘制数据 [英] Matplotlib: data being plotted over legend when using twinx

查看:33
本文介绍了Matplotlib:使用 twinx 时在图例上绘制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python和Matplotlib绘制许多不同的数据集.我正在使用twinx在主轴上绘制一个数据集,在次级轴上绘制另一个数据集.对于这些数据集,我想有两个单独的图例.

I'm trying to use Python and Matplotlib to plot a number of different data sets. I'm using twinx to have one data set plotted on the primary axis and another on the secondary axis. I would like to have two separate legends for these data sets.

在我当前的解决方案中,辅助轴的数据绘制在主轴图例的顶部,而主轴数据不绘制在辅助轴图例上.

In my current solution, the data from the secondary axis is being plotted over the top of the legend for the primary axis, while data from the primary axis is not being plotted over the secondary axis legend.

我根据此处的示例生成了一个简化版本:http://matplotlib.org/users/legend_guide.html

I have generated a simplified version based on the example here: http://matplotlib.org/users/legend_guide.html

这是我目前所拥有的:

import matplotlib.pyplot as plt
import pylab

fig, ax1 = plt.subplots()
fig.set_size_inches(18/1.5, 10/1.5)
ax2 = ax1.twinx()

ax1.plot([1,2,3], label="Line 1", linestyle='--')
ax2.plot([3,2,1], label="Line 2", linewidth=4)

ax1.legend(loc=2, borderaxespad=1.)
ax2.legend(loc=1, borderaxespad=1.)

pylab.savefig('test.png',bbox_inches='tight', dpi=300, facecolor='w', edgecolor='k')

结果如下图所示:

如图所示,来自 ax2 的数据绘制在 ax1 图例上,我希望图例位于数据顶部.我在这里缺少什么?

As shown in the plot, the data from ax2 is being plotted over the ax1 legend and I would like the legend to be over the top of the data. What am I missing here?

感谢您的帮助.

推荐答案

您可以将以下图例设置行替换为:

You could replace your legend setting lines with these:

ax1.legend(loc=1, borderaxespad=1.).set_zorder(2)
ax2.legend(loc=2, borderaxespad=1.).set_zorder(2)

它应该可以解决问题.

请注意,位置已更改为与各行相对应,并且在定义图例之后应用了 .set_zorder()方法.

Note that locations have changed to correspond to the lines and there is .set_zorder() method applied after the legend is defined.

zorder 中较高的整数表示将在其上绘制的较高"层.

The higher integer in zorder the 'higher' layer it will be painted on.

这篇关于Matplotlib:使用 twinx 时在图例上绘制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆