Reputation:
Here is my code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.canvas.draw()
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'Inbox'
labels[1] = 'Sent'
labels[2] = 'Important'
labels[3] = 'Starred'
labels[4] = 'Unread'
ax.set_xticklabels(labels)
plt.plot([1500,1200,900,600,300])
plt.show()
As you can see, i only want 5 labels on the x axis. However when i run the graph, it produces 8 avaiable slots for labels. The first 5 are my labels as desired, however the last 3 are blank. How do i only set the 5 labels i want?
Upvotes: 1
Views: 2595
Reputation: 10650
This is because the plot is not only drawing points for the points you specify, but additional ones too. The problem is obvious if you don't change the axis labels:
If you want to have 5 ticks for your data, then you need to set their locations as well, using set_xticks()
- if you don't then you just replace the tick labels for the ticks that already exist, which is not what you want.
But this is besides the point, this kind of data should not be represented with a line like this, you should use a bar chart:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x_locs = np.arange(5)
width = 0.9
email_labels = ["Inbox", "Sent", "Important", "Starred", "Unread"]
email_volumes = [1500, 1200, 900, 600, 300]
ax.bar(x_locs-width/2.0, email_volumes, width)
ax.set_xticks(x_locs)
ax.set_xticklabels(email_labels)
plt.show()
Upvotes: 2