pythonpython-3.xxticksyticks

How to create same ticks and labels on both axes?


I have to create a plot on which ticks and labels are specifically defined; an example of reproducible plot is given below:

import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-v0_8')

fig, ax = plt.subplots(figsize=(4, 4))

ticks = [0.00, 0.25, 0.50, 0.75, 1.00]

ax.set_xticks(ticks)
ax.set_xticklabels(ticks, weight='bold', size=8)
ax.set_yticks(ticks)
ax.set_yticklabels(ticks, weight='bold', size=8)

plt.show()

As ticks and labels are exactly the same of both axes, is there a way to set them as a single command ? Something mixing both xticks and yticks ?


Solution

  • You can use a function.

    import matplotlib.pyplot as plt
    plt.style.use('seaborn-v0_8')
    
    def set_ticks_and_labels(ax, t, **kwargs):
        ax.set_xticks(t)
        ax.set_xticklabels(t, **kwargs)
        ax.set_yticks(t)
        ax.set_yticklabels(t, **kwargs)
    
    fig, ax = plt.subplots(figsize=(4, 4))
    
    ticks = [0.00, 0.25, 0.50, 0.75, 1.00]
    set_ticks_and_labels(ax, ticks, weight='bold', size=8)
    
    plt.show()