Main axis are not shown when using grid

家住魔仙堡 提交于 2019-12-25 07:09:49

问题


I want to plot two graphs into the same figure with two different y-axis. In addition to it, I would like to add a grid and then save the plot as pdf.

My problem is that - while the grid is drawn correctly - the main axis are not shown anymore. How can they be plotted as well? I am using matplotlib 1.5.1 and Python 2.7.11.

Here is the plot:

And here is the code I am using:

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:


It works for me with the plot correctly showing the axis like on the png added here under.

Same output for the following:

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

The code used is this one - same as the one posted except for the plt.show() that I added to produce the png image.

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)

If you are using an ipython kernel, there might be some residual settings from previous work interfering with the rendering? Have you tried with a fresh kernel?



来源:https://stackoverflow.com/questions/36467770/main-axis-are-not-shown-when-using-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!