【问题标题】:How to get different number of ticks and labels in matplotlib?如何在 matplotlib 中获得不同数量的刻度和标签?
【发布时间】:2016-08-23 02:35:41
【问题描述】:

我不知道如何在保留刻度数的同时减少绘图中的刻度数标签。有没有办法做到这一点,或者我只能有与标签数量一样多的刻度?谢谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    为一些刻度设置空刻度标签。

    # based on http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html
    import matplotlib.pyplot as plt
    x = [1, 2, 3, 4]
    y = [1, 4, 9, 6]
    labels = ['Frogs', 'Hogs', '', 'Slogs']
    
    plt.plot(x, y, 'ro')
    # You can specify a rotation for the tick labels in degrees or with keywords.
    plt.xticks(x, labels, rotation='vertical')
    # Pad margins so that markers don't get clipped by the axes
    plt.margins(0.2)
    # Tweak spacing to prevent clipping of tick-labels
    plt.subplots_adjust(bottom=0.15)
    plt.show()
    

    【讨论】:

    • 酷!就快到了!那么我应该如何用大量数据定义这些标签(当我的标签是数字时)?例如,如果 x=np.arange(0,100,1) 并且我希望我的标签位于 10、20 等处?我尝试了 labels = np.arange(0,100,10),但它没有用...谢谢
    • 好的,我想出了如何绕过它。只需一个可除的 if 循环!
    【解决方案2】:

    只是为了回答我对 Serenity 答案的评论,以下是获取数字标签的方法。

    x = range(100)
    labels = []
    for i in x:
        if i % 10 == 0:
            i=i
        else:
            i=' '
        labels.append(i)
    

    这样就可以了。

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 2012-03-14
      • 2021-06-14
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      相关资源
      最近更新 更多