pythonmatplotliblabelseaborn

How to extract the (major/minor) ticks from a seaborn plot?


I am trying to extract ticks from my python plot drawn with seaborn. I have two sets of code below which I thought would produce same results. However, one extracts the ticks correctly and the other just returns zeros.

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

ax = fig.gca()

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)

ax.plot(t, s)

plt.show()


print([p.label.get_position()[0] for p in ax.xaxis.get_major_ticks()])
print([p.label.get_position()[0] for p in ax.xaxis.get_minor_ticks()])
print([p.label.get_position()[1] for p in ax.yaxis.get_major_ticks()])
print([p.label.get_position()[1] for p in ax.yaxis.get_minor_ticks()])

Output:

[-20.0, 0.0, 20.0, 40.0, 60.0, 80.0, 100.0, 120.0]
[]
[-1.0, -0.75, -0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0, 1.25]
[]

The other piece of code is with seaborn:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

fig = plt.figure()

ax = fig.gca()
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)

data = pd.DataFrame()
data['x'] = t
data['y'] = s
display(data)

sns_plot = sns.scatterplot(x='x', y='y', data=data, ax=ax)
sns_plot.set_title("test plot")

print([p.label.get_position()[0] for p in ax.xaxis.get_major_ticks()])
print([p.label.get_position()[0] for p in ax.xaxis.get_minor_ticks()])
print([p.label.get_position()[1] for p in ax.yaxis.get_major_ticks()])
print([p.label.get_position()[1] for p in ax.yaxis.get_minor_ticks()])

Output:

[0, 0, 0, 0, 0, 0, 0, 0]
[]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[]

Can someone point out how I can extract the tick labels from my seaborn plot? Or point out what is wrong in the second block of code?

Thanks!


Solution

  • Your second block of code lies in how Seaborn interacts with Matplotlib. Seaborn often overrides or adjusts the tick properties, so the tick labels are not immediately accessible in the same way as a plain Matplotlib plot.

    To extract the major and minor ticks from a Seaborn plot, you can use the underlying ax object to explicitly access the tick locations or labels after the Seaborn plot has been rendered.

    import seaborn as sns
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    t = np.arange(0.0, 100.0, 0.1)
    s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)
    data = pd.DataFrame({'x': t, 'y': s})
    
    fig, ax = plt.subplots()
    sns.scatterplot(x='x', y='y', data=data, ax=ax)
    ax.set_title("Test Plot")  
    x_major_ticks = ax.get_xticks()
    x_minor_ticks = ax.get_xticks(minor=True)
    y_major_ticks = ax.get_yticks()
    y_minor_ticks = ax.get_yticks(minor=True) 
    print("X-axis Major Ticks:", x_major_ticks)
    print("X-axis Minor Ticks:", x_minor_ticks)
    print("Y-axis Major Ticks:", y_major_ticks)
    print("Y-axis Minor Ticks:", y_minor_ticks) 
    plt.show()