Skip to content Skip to sidebar Skip to footer

Matplotlib's Get_ticklabels Not Working With Custom String Labels

I would like to plot only every 50th item from 'dates' as a tick on the x axis. When I comment out the line 'plt.xticks(xticks, dates)', it works fine (top figure), but when I atte

Solution 1:

The following should work:

ax = plt.axes()

pos = np.arange(len(vals))
ax.bar(pos, vals)

ax.set_xticks(pos[::50])ax.set_xticklabels(np.array(dates)[::50], rotation=90)

Solution 2:

You try to set every 50th label visible. But all the others are visible anyways, so all are visible, plus those you set visible. Of course you could instead set some invisible; but maybe a better solution is to not even create the labels in the first place?

To tick and label every 50th entry you can slice the lists of ticks and labels.

import matplotlib.pyplot as plt
from datetime import datetime, date
import numpy as np

vals = [10, 11, ....]
dates =['05/01/2018', '05/02/2018', ....]
xticks = np.arange(len(vals))

ax = plt.axes()
ax.bar(xticks,vals)

plt.xticks(xticks[::50], dates[::50], rotation=90)

plt.show()

enter image description here

Note however, that just plotting the dates as datetimes would give you some very nice formatting automatically.

import matplotlib.pyplotas plt
from datetime import datetime

vals = [10, 11, ..., 1]
dates =['05/01/2018', '05/02/2018', ..., '12/05/2018']
dates = [datetime.strptime(s, "%m/%d/%Y") for s in dates]

ax = plt.axes()
ax.bar(dates,vals)

plt.show()

enter image description here

Post a Comment for "Matplotlib's Get_ticklabels Not Working With Custom String Labels"