adding extra axis ticks using matplotlib

前端 未结 2 1851
Happy的楠姐
Happy的楠姐 2021-01-31 02:12

I have a simple plot code as

plt.plot(x,y)
plt.show()

I want to add some extra ticks on the x-axis in addition to the current ones, let\'s say

2条回答
  •  遇见更好的自我
    2021-01-31 02:46

    For the sake of completeness, I would like to give the OO version of @Lev-Levitsky's great answer:

    lines = plt.plot(x,y)
    ax = lines[0].axes
    ax.set_xticks(list(ax.get_xticks()) + extraticks)
    

    Here we use the Axes object extracted from the Lines2D sequence returned by plot. Normally if you are using the OO interface you would already have a reference to the Axes up front and you would call plot on that instead of on pyplot.

    Corner Caveat

    If for some reason you have modified your axis limits (e.g, by programatically zooming in to a portion of the data), you will need to restore them after this operation:

    lim = ax.get_xlim()
    ax.set_xticks(list(ax.get_xticks()) + extraticks)
    ax.set_xlim(lim)
    

    Otherwise, the plot will make the x-axis show all the available ticks on the axis.

提交回复
热议问题