Search code examples
pythonmatplotlibplotaxis-labels

How to variate different xtick distances within a single x-axis?


How do I adjust the x-axis of a plot in such that certain ticks are spaced at a certain distance whereas the other ticks are spaced wider apart?

For instance, in the following plot, I would like for the 1-200 tick to be spaced twice the distance apart from 201-300 (ie. twice the current distance), while the rest of the xticks retain the spacings as they are at the moment.

enter image description here


Solution

  • The axis in a plot is linear. This means the distance between any two values plottet on the axis is proportional to their respective difference. The ticks behave the same and are bound to the axis scale. E.g. two ticks at 1 and 2 are as far apart as two ticks at 0.5 and 1.5.

    You may of course relabel the ticks the way you want, and also position them as you want, using ax.set_xticks() and ax.set_xticklabels().

    enter image description here

    This however does not change the data spacing. So in order to have a larger space between two data points, the data itself needs to be spaced further apart, e.g.

    ax.plot([4,6,7,8],[23,24,23,24], marker="o")
    ax.set_xticks([4,6,7,8])
    

    enter image description here

    Using ax.set_ticklabels now allows to set labels to anything desired.