mane
mane

Reputation: 2233

Python plot x-axis display only select items

I have a python matplotlib graph showing up as below.

There are over 100 items on the X-axis and I DO want to plot them all, but want only about 25 or so (maybe automatically) so that it is clear to look at.

Can you please help?

Thanks

My code is also as follows:

l1 = plt.plot(b)
plt.setp(l1, linewidth=4, color='r')
l2 = plt.plot(c)
plt.setp(l2, linewidth=4, color='k')
l3 = plt.plot(d)
plt.setp(l3, linewidth=4, color='g')
plt.xticks(range(len(a)), a)
plt.xticks(rotation=30)
plt.show()
plt.savefig('a.png')

NOTE: I also have the data column a (the X-axis variable) in the form

u' 2016-02-29T00:01:30.000Z CHEPSTLC0007143 CDC-R114-DK'

which throws this error invalid literal for float(). That is the reason I am using plt.xticks(range(len(a)), a).

Upvotes: 9

Views: 25340

Answers (3)

Raghav Arora
Raghav Arora

Reputation: 186

If you want to show only 3 ticks, use the following code:

axes = plt.axes()
x_values = axes.get_xticks()
y_values = axes.get_yticks()

x_len = len(x_values)
y_len = len(y_values)
print(x_len)
print(y_len)

new_x = [x_values[i] for i in [0, x_len // 2, -1]]
new_y = [y_values[i] for i in [0, y_len // 2, -1]]

axes.set_xticks(new_x)
axes.set_yticks(new_y)

Similarly, if you want to show only 25 ticks, just pick up equally spaced 25 values from your get_xticks()

Upvotes: 0

Guilherme Viegas
Guilherme Viegas

Reputation: 489

Just replace plt.xticks(range(len(a)), a) by plt.xticks(np.arange(0, len(a) + 1, 5)) and you are gonna reduce the number of x axis labels displayed.

Upvotes: 1

tacaswell
tacaswell

Reputation: 87376

This is a case where mpl is doing exactly what you told it to, but what you told it to do is sort of inconvenient.

plt.xticks(range(len(a)), a)

is telling mpl to put a tick at every integer and to use the strings in a to label the ticks (which it is correctly doing). I think instead you want to be doing something like

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

# synthetic data
a = list(range(45))
d = ['the label {}'.format(i) for i in range(45)]

# make figure + axes
fig, ax = plt.subplots(tight_layout=True)
ax.set_xlabel('x label')
ax.set_ylabel('y label')

# draw one line
ln1, = ax.plot(range(45), lw=4, color='r')


# helper function for the formatter
def listifed_formatter(x, pos=None):
    try:
        return d[int(x)]
    except IndexError:
        return ''

# make and use the formatter
mt = mticker.FuncFormatter(listifed_formatter)
ax.xaxis.set_major_formatter(mt)

# set the default ticker to only put ticks on the integers
loc = ax.xaxis.get_major_locator()
loc.set_params(integer=True)

# rotate the labels
[lab.set_rotation(30) for lab in ax.get_xticklabels()]

example output

If you pan/zoom the ticklabels will be correct and mpl will select a sensible number of ticks to show.

[side note, this output is from the 2.x branch and shows some of the new default styling]

Upvotes: 5

Related Questions