Search code examples
pythonmatplotlibseabornxticks

How to rotate specific tick labels


Use case: you have tick marks on the x axis. But some ticks are either too close or you need to otherwise emphasize them via rotation. So, for example, you might have a list of dates across the x axis that are always first of the month. But then you want to 'call out' one date in particular, say your birthday, and rotate it, say, 25 degrees.

How could you rotate that one 'tick' while NOT rotating all the others?

I know plt.xticks(rotation = 335) will rotate all the ticks nicely.

But let's say you have:

f, ax = plt.subplots(figsize=(16, 8))

ax.set_xticks((0,1455,5000,10000,15000,20000,25000,30000))

and you want to rotate 1455 by 335 degrees, while NOT rotating any of the others.

How do you do it?


Solution

  • After you set the tick positions (and optionally also set their labels), you can access the matplotlib text elements via ax.get_xticklabels(). So, you can just access the second element in the list and change its rotation. (Similarly, you can e.g. change colors.)

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(figsize=(16, 8))
    ax.set_xticks((0, 1455, 5000, 10000, 15000, 20000, 25000, 30000))
    ticks = ax.get_xticklabels()
    ticks[1].set_rotation(335)
    plt.show()
    

    rotating one tick label

    This applies to pandas.DataFrame.plot, matplotlib, and seaborn.