Prevent grid lines from twin axis to be drawn on top of artists from original axis

可紊 提交于 2021-02-08 06:54:45

问题


I have an axis on which I plot some data and I have another twin axis which I use to draw grid lines at specific tick positions (other than the ticks of the original axis):

import matplotlib.pyplot as plt
import numpy as np

f, ax = plt.subplots()
ax.set_xlim([0, 1])
ax2 = ax.twiny()
ax2.set_xlim([0, 1])
ax2.set_xticks(np.linspace(0, 1, 11))
ax2.xaxis.grid()
x = np.linspace(0, 1, 100)
ax.plot(x, np.sin(x), label='sin(x)')
ax.legend()
plt.show()

Now this has the undesirable effect that the grid lines of the twin axes are drawn on top of the legend and line plot of the original axis. As far as I understand this is because matplotlib draws the axes in the order they were created and for that reason zorder won't help (because zorder only specifies the order among the artists of a single axis).

I know I could plot the data on the twin axis ax2 instead (followed by ax2.legend()) but I'd prefer to have the setup as is. Instead changing the order in which the two axes are drawn should solve the problem, but I couldn't figure out how to do that. There is f.get_axes() which seems to return the axes in the order they were created but no option to revert it.

Or maybe there exists even another solution?


回答1:


You can change the zorder of the axes themselves.

ax.set_zorder(2)
ax2.set_zorder(1)
ax.patch.set_visible(False)



来源:https://stackoverflow.com/questions/55996069/prevent-grid-lines-from-twin-axis-to-be-drawn-on-top-of-artists-from-original-ax

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