【问题标题】:add custom tick with matplotlib使用 matplotlib 添加自定义刻度
【发布时间】:2018-03-25 00:37:39
【问题描述】:

我想在matplotlib 图中添加一个自定义刻度。目前,我使用以下命令(例如)添加我的刻度:

axis.set_yticks([0.5,0.6,0.7,0.8,0.9,1.0])

我希望能够做到:

axis.set_yticks({ 1.0 : "some custom text"})

所以在那个位置显示some custom text,而不是1.0

注意:我从 4 年前就发现了这个问题。我问的问题基本相同,希望有更好的方法: Adding a custom tick and label

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    其他问题及其答案仍然有效。您不能使用字典来设置刻度。

    但是,在这种情况下,您的要求似乎有所不同。虽然链接的问题要求保持刻度不变,但无论如何您都希望手动设置刻度。这将需要设置刻度 刻度标签,但随后允许在设置标签时将字典中的任何键替换为相应的值。

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    ticks = [0.5,0.6,0.7,0.8,0.9,1.0]
    ax.set_yticks(ticks)
    
    dic = { 1.0 : "some custom text"}
    labels = [ticks[i] if t not in dic.keys() else dic[t] for i,t in enumerate(ticks)]
    ## or 
    # labels = [dic.get(t, ticks[i]) for i,t in enumerate(ticks)]
    
    ax.set_yticklabels(labels)
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2014-04-10
      • 2016-04-27
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多