代码之家  ›  专栏  ›  技术社区  ›  Sun Bear

如何修改matplotlib x轴ticklabels?

  •  0
  • Sun Bear  · 技术社区  · 4 年前

    以下是一个示例代码:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    import numpy as np
    import math
    x = np.arange(0, math.pi*2, 0.05)
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    y = np.sin(x)
    ax.plot(x, y, marker='s')
    ax.set_xlabel('angle')
    ax.set_title('sine')
    #ax.set_xticklabels([" ",1,2,3,4,5," "]) # don't work
    ax.set_yticks([-1,0,1])
    plt.show()
    

    它创建了这个图:

    Figure 1

    对于x轴,我想修改x轴的ticklabels,只显示1,2,3,4,5,而我想空白0和6。我试过了 ax.set_xticklabels([" ",1,2,3,4,5," "]) 但这并没有奏效。我得到的结果是:

    wrong

    以及此警告消息:

    Warning (from warnings module):
      File "~/test.py", line 12
        ax.set_xticklabels(["",1,2,3,4,5,""]) # don't work
    UserWarning: FixedFormatter should only be used together with FixedLocator
    

    如何修改x轴ticklabels以仅显示1,2,3,4,5?

    1 回复  |  直到 4 年前
        1
  •  1
  •   jylls    4 年前

    你可以设定标准 ax.set_xticks 在打电话给您之前 ax.set_xticklabels 作用 请参阅以下代码:

    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    import numpy as np
    import math
    x = np.arange(0, math.pi*2, 0.05)
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    y = np.sin(x)
    ax.plot(x, y, marker='s')
    ax.set_xlabel('angle')
    ax.set_title('sine')
    ax.set_xticks(np.arange(7))
    ax.set_xticklabels([" ",1,2,3,4,5," "]) 
    ax.set_yticks([-1,0,1])
    plt.show()
    

    输出给出:

    enter image description here