首页 文章

如何使用matplotlib将单个标记的刻度附加到x轴?

提问于
浏览
2

假设我在matplotlib中设置了一个简单的绘图:

fig, ax = plt.subplots(1,1)
p=ax.plot([1,2,3,4,5], [10,9,8,7,6])

如何在值为1.5的x轴上添加勾号,标签为“此处为1.5”?

我知道我可以使用 plt.xticks() ,但是我需要指定所有的刻度和标签 .

1 回答

  • 2

    这样的东西会起作用:

    import matplotlib.pyplot as plt
    
    x=range(10)
    y=range(10)
    
    fig, ax = plt.subplots(1,1)
    p=ax.plot(x,y)
    ax.set_xticks([1.5])
    ax.set_xticklabels(["Here is 1.5"])
    fig.show()
    

    enter image description here

    如果您想添加额外的x-tick:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x=range(10)
    y=range(10)
    
    fig, ax = plt.subplots(1,1)
    
    p=ax.plot(x,y)
    
    xt = ax.get_xticks() 
    xt=np.append(xt,1.5)
    
    xtl=xt.tolist()
    xtl[-1]="Here is 1.5"
    ax.set_xticks(xt)
    ax.set_xticklabels(xtl)
    
    fig.show()
    

    enter image description here
    如果需要,您可以使用标签旋转 .

相关问题