1

I am trying to plot a graph using matplotlib. The challenge arises, as I want to keep all of the tick labels on the x axis, except for 0 which I want to change to 1.

I will be doing a lot of plots, with different x-lims, so the solution needs to work in more than just one specific case. So far I have tried the following:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# axis limits
ax.set_xlim(-50, 50)
ax.set_ylim(0, None)


# labels for axis
ax.set_xlabel('Year')
ax.set_ylabel('Frequency')


# ensuring that a tick is never 0 but rather 1 on the x-axis
locs = ax.get_xticks()
labels = ax.get_xticklabels()

if 0 in locs:
    new_labels = [i for i in labels]
    new_labels[np.where(locs==0)[0][0]] = plt.Text(0.0, 0, '1')
    ax.set_xticklabels(new_labels)


 
plt.tight_layout()

enter image description here

print(new_labels)
###OUTPUT###
[Text(-60.0, 0, ''), Text(-40.0, 0, ''), Text(-20.0, 0, ''), Text(0.0, 0, '1'), Text(20.0, 0, ''), Text(40.0, 0, ''), Text(60.0, 0, '')]

The problem here, is that the string in all the Text objects are empty except for '1'. However, the variable new_labels does contain labels for all xticks if I comment out the ax.set_xticklabels(new_labels) line like seen in the following code:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# axis limits
ax.set_xlim(-50, 50)
ax.set_ylim(0, None)


# labels for axis
ax.set_xlabel('Year')
ax.set_ylabel('Frequency')


# ensuring that a tick is never 0 but rather 1 on the x-axis
locs = ax.get_xticks()
labels = ax.get_xticklabels()

if 0 in locs:
    new_labels = [i for i in labels]
    new_labels[np.where(locs==0)[0][0]] = plt.Text(0.0, 0, '1')
    #ax.set_xticklabels(new_labels)

 
plt.tight_layout()

enter image description here

print(new_labels)
###OUTPUT###
[Text(-60.0, 0, '−60'), Text(-40.0, 0, '−40'), Text(-20.0, 0, '−20'), Text(0.0, 0, '1'), Text(20.0, 0, '20'), Text(40.0, 0, '40'), Text(60.0, 0, '60')]

I am not sure what is going on when I am setting the new xtick-labels? It also might be, that i am trying to do this in an unnecessarily complicated way?

  • 1
    I think this is because matplotlib isn't populating the xticklabels until drawing happens. In your case you can just do `ax.set_xticklabels([i if i != 0 else 1 for i in ax.get_xticks()])` – tomjn Feb 19 '22 at 18:00

0 Answers0