使用网格时不显示主轴

时间:2016-04-07 05:55:58

标签: python matplotlib plot axis grid-layout

我想将两个图形绘制到具有两个不同y轴的同一图形中。除此之外,我想添加一个网格,然后将该图保存为pdf。

我的问题是 - 在正确绘制网格时 - 主轴不再显示。它们如何被绘制?我正在使用matplotlib 1.5.1Python 2.7.11

这是情节:

enter image description here

这是我正在使用的代码:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

pp = PdfPages('myplot.pdf')

x = np.linspace(0.1, 10, 100)
y1 = np.exp(x)
y2 = np.log(x)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1, '-ro', markersize=5, label='y1')
ax1.set_ylim(-0.1, 1.1 * max(y1))
ax1.set_ylabel('y1', fontsize=20)
ax1.legend(loc='upper left')
ax1.grid(ls='dotted', c='k')
ax1.patch.set_facecolor('white')

ax2 = ax1.twinx()
ax2.grid(False)
ax2.plot(x, y2, 'b-', label='y2')
ax2.set_ylim(-0.1, 1.1 * max(y2))
ax2.set_ylabel('y2', fontsize=20)
ax2.legend(loc='upper right')
plt.xlim([-0.5, 1.05 * max(x)])
ax1.set_xlabel('x', fontsize=20)

pp.savefig(fig)
pp.close()
plt.close(fig)

1 个答案:

答案 0 :(得分:1)

对我而言,正确显示轴上的轴就像在png上添加的那样。

以下相同的输出:

  • Python 3.4.4, iPython, Jupyter notebook, matplotlib 1.5.1
  • Python 2.7.11, iPython, Jupyter notebook, matplotlib 1.5.?

enter image description here

使用的代码是这一个 - 与发布的代码相同,除了我为生成png图像而添加的plt.show()。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

pp = PdfPages('myplot.pdf')

x = np.linspace(0, 10, 100)
y1 = np.exp(x)
y2 = np.log(x)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1, '-ro', markersize=5, label='y1')
ax1.set_ylim(-0.1, 1.1 * max(y1))
ax1.set_ylabel('y1', fontsize=20)
ax1.legend(loc='upper left')
ax1.grid(ls='dotted', c='k')
ax1.patch.set_facecolor('white')

ax2 = ax1.twinx()
ax2.grid(False)
ax2.plot(x, y2, 'b-', label='y2')
ax2.set_ylim(-0.1, 1.1 * max(y2))
ax2.set_ylabel('y2', fontsize=20)
ax2.legend(loc='upper right')
plt.xlim([-0.5, 1.05 * max(x)])
ax1.set_xlabel('x', fontsize=20)

#plt.show()

pp.savefig(fig)
pp.close()
plt.close(fig)

如果您使用的是ipython内核,以前的工作可能会有一些残留设置干扰渲染?你尝试过新鲜的内核吗?