我试图绘制出两个不同数量级的数据集经过一些研究(实际上是一次谷歌搜索),我发现了twinx()函数。
不过,我在使用时遇到了一些麻烦我正在用这个工具制作出版物级别的图表,有件事困扰着我。
系统:Ubuntu上的matplotlib v1.3.1、python v2.7.4
请考虑以下代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from matplotlib.ticker import AutoMinorLocator


time = np.arange(0, 365, 1)
y1 = np.random.rand(len(time)) * np.exp(-0.03 * time)
y2 = 0.001 * np.random.rand(len(time)) * np.exp(-0.02 * time)

for i in range(30):
    y2[-i] = 0

fig = plt.figure(figsize=(8,6), dpi=300)
fig.subplots_adjust(hspace=0.0, right=0.9, top=0.94, left=0.12, bottom=0.07)
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

for tl in ax1.get_yticklabels():
    tl.set_color('r')
for tl in ax2.get_yticklabels():
    tl.set_color('b')

for ax in [ax1, ax2]:
    ax.yaxis.set_major_locator(MaxNLocator(
        nbins=5,
        steps=[1,2,3,4,5,10],
        integer=False,
        symmetric=False,
        prune=None))
    ax.yaxis.set_minor_locator(AutoMinorLocator(4))

ax2.plot(time, y1, 'b-')
ax1.plot(time, y2, 'r-')
ax1.set_ylabel(r"y value", labelpad=15)
ax1.set_xlabel(r"x value")
ax1.set_xlim(0,365)
ax1.set_xticks(range(0,370,30))
ax1.xaxis.set_minor_locator(AutoMinorLocator(3))

fig.savefig("Errorplot.png", dpi=60)

现在,当我看到这个低分辨率的输出时,我觉得没有什么奇怪的:
但是,当放大高分辨率(例如,dpi=300)版本时,我看到以下内容:
很明显,第二个轴上的线是在第一个轴的脊椎上画的。
如何缓解这个问题?是否有方法重新绘制axes实例的脊椎?
我试过的
更改plot()调用的顺序
zorderkwarg设置为-1,-10即使当ax2 zorder比ax1小的时候,我也有这种行为。
结合以上内容:ax2.spines['bottom'].set_zorder(10)

最佳答案

这篇文章似乎没有得到很多意见,但我发现它很有帮助,我想添加另一种方法来改变zorder的机会,它将帮助其他人这个post更接近我想要做的,但重要的是改变zorder,这是@Ffisegydd概述的另一种方法是使用以下方法:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.set_zorder(ax2.get_zorder()+1) # put ax1 in front of ax2
ax1.patch.set_visible(False) # hide the 'canvas'

ax1.plot(data1[:,0], data1[:,0])  # plot whatever data you want
ax2.plot(data2[:,0], data2[:,0])  # plot commands can precede the set_zorder command

我意识到这并不能直接解决问题,但希望它能帮助像我这样的人找到这篇文章,寻找一个密切相关的问题的解决方案。

关于python - Matplotlib错误:使用twinx()在脊柱上方显示数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22942984/

10-09 08:02