Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 229
mane Avatar asked Oct 18 '22 14:10

mane


1 Answers

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]

like image 106
tacaswell Avatar answered Nov 03 '22 06:11

tacaswell