代码之家  ›  专栏  ›  技术社区  ›  Michael Kuhn

如何删除Matplotlib中的顶部和右侧轴?

  •  86
  • Michael Kuhn  · 技术社区  · 15 年前

    我只想使用左轴和底轴,而不是默认的“框”轴样式,即:

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

    这应该很容易,但我在文档中找不到必要的选项。

    6 回复  |  直到 6 年前
        1
  •  85
  •   divenex    7 年前

    这是官方网站上建议的Matplotlib 2.0解决方案 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()
    

    enter image description here

        2
  •  59
  •   timday    13 年前

    或者,这个

    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()
    

    似乎可以在不丢失旋转标签支持的情况下在轴上实现相同的效果。

    (Matplotlib 1.0.1;解决方案灵感来自 this )

        3
  •  31
  •   Oren    7 年前

    [编辑]Matplotlib in now(2013-10)on version 1.3.0,其中包括

    这个能力实际上是刚刚添加的,你需要它的颠覆版本。您可以看到示例代码 here .

    我只是想说有更好的 example 在线现在。尽管还需要颠覆版本,但还没有发布。

    [编辑]Matplotlib 0.99.0 RC1刚刚发布,包括此功能。

        4
  •  9
  •   nikow    13 年前

    如果不需要记号等(例如用于绘制定性插图),也可以使用此快速解决方法:

    使轴不可见(例如 plt.gca().axison = False )然后用 plt.arrow .

        5
  •  5
  •   Evgeni Sergeev    7 年前

    (除了这里的综合答案之外,这更像是一个扩展注释。)


    请注意,我们可以单独隐藏这三个元素中的每一个:

    • 要隐藏边框(又名“脊椎”): ax.set_frame_on(False) ax.spines['top'].set_visible(False)

    • 要隐藏刻度: ax.tick_params(top=False)

    • 要隐藏标签: ax.tick_params(labeltop=False)

        6
  •  2
  •   Sander van den Oord    6 年前

    library seaborn内置了函数disine()。

    只需添加:

    import seaborn as sns
    

    现在创建图形。最后加上:

    sns.despine()
    

    如果查看函数的某些默认参数值,它将删除顶部和右侧脊椎,并保留底部和左侧脊椎:

    sns.despine(top=True, right=True, left=False, bottom=False)
    

    请在此处查看更多文档: https://seaborn.pydata.org/generated/seaborn.despine.html