Search code examples
matplotlibxticks

How to label only certain x-ticks matplotlib?


In this diagram I have distributed the ticks and applied a tick:

ax.set_xticks(np.arange(0, 800, 1))
ax.grid()

How can I label on the x-axis only the numbers present in the legend?

Plot

Regards,

Karl


Solution

  • Try this to keep all grid points, but only label the points of interest.

    original_labels = [str(label) for label in ax.get_xticks()]
    labels_of_interest = [str(i) for i in np.arange(235,295,5)]
    new_labels = [label if label in labels_of_interest else "" for label in original_labels]
    ax.set_xticklabels(new_labels)
    

    Edit:

    an optional parameter to ax.set_xticklabels is rotation. If you find your labels are still overlapping, try rotating them:

    ax.set_xticklabels(new_labels, rotation=45) #rotate labels 45 degrees