How can I remove the top and right axis in matplotlib?

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

Instead of the default "boxed" axis style I want to have only the left and bottom axis, i.e.:

+------+         | |      |         | |      |   --->  | |      |         | +------+         +------- 

This should be easy, but I can't find the necessary options in the docs.

回答1:

This is the suggested Matplotlib 2.0 solution from the official website HERE:

import numpy as np import matplotlib.pyplot as plt  x = np.linspace(0, 2*np.pi, 100) y = np.sin(x)  ax = plt.subplot(111) ax.plot(x, y)  # Hide the right and top spines ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False)  # Only show ticks on the left and bottom spines ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom')  plt.show() 



回答2:

Alternatively, this

def simpleaxis(ax):     ax.spines['top'].set_visible(False)     ax.spines['right'].set_visible(False)     ax.get_xaxis().tick_bottom()     ax.get_yaxis().tick_left() 

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).



回答3:

[edit] matplotlib in now (2013-10) on version 1.3.0 which includes this

That ability was actually just added, and you need the Subversion version for it. You can see the example code here.

I am just updating to say that there's a better example online now. Still need the Subversion version though, there hasn't been a release with this yet.

[edit] Matplotlib 0.99.0 RC1 was just released, and includes this capability.



回答4:

If you don't need ticks and such (e.g. for plotting qualitative illustrations) you could also use this quick workaround:

Make the axis invisible (e.g. with plt.gca().axison = False) and then draw them manually with plt.arrow.



回答5:

(This is more of an extension comment, in addition to the comprehensive answers here.)


Note that we can hide each of these three elements independently of each other:

  • To hide the border (aka "spine"): ax.set_frame_on(False) or ax.spines['top'].set_visible(False)

  • To hide the ticks: ax.tick_params(top=False)

  • To hide the labels: ax.tick_params(labeltop=False)



回答6:

This is much more rudimentary, but might do the trick:

remove_border()



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