4

I am using matplotlib to make a scatter plot, and the x-axis labels are running together to the point they are illegible. Here's all the relevant code:

plt.xticks(rotation=30)
plt.scatter(x,y)
plt.show()

x and y are lists of x-axis values and y-axis values, respectively.

This SO post (How to prevent x-axis labels from overlapping) asks the same question, but if there's an answer anywhere in there, I can't tease it out.

This SO post (Cleanest way to hide every nth tick label in matplotlib colorbar?) asks a similar question in the context of colorbars. All of the responses that seem to work for people are of the form

for label in cbar.ax.xaxis.get_ticklabels()[::2]:
    label.set_visible(False)

or

plt.setp(cbar.ax.get_xticklabels()[::2], visible=False)

where cbar is the asker's colorbar object. Every time I try to adapt these solutions to my case, for example

plt.xticks(rotation=30)
plot = plt.scatter(x,y)
plt.setp(plot.get_xticklabels()[::2], visible=False)
plt.show()

I get errors like

AttributeError: 'PathCollection' object has no attribute 'get_xticklabels'.

Similar to the above, if I try plot.ax.get_xticklabels() I get AttributeError: 'PathCollection' object has no attribute 'ax', etc.

How do I show only every nth axis label?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
PiotrChernin
  • 441
  • 8
  • 18
  • 1
    `plot.axes.get_xticklabels()` However, you shouldn't come into the situation of too many ticklabels in the first place, because matplotlib by default only shows some maximum of 10 ticks or so. This means, something else is not correct (or at least not ideal) in your script, and you'd better be asking about that one instead. – ImportanceOfBeingErnest Jul 15 '19 at 22:05
  • @ImportanceOfBeingErnest That's it, thank you! – PiotrChernin Jul 15 '19 at 22:44

1 Answers1

0

This worked: first, set all labels to not visible, then make every N labels visible.

plot = plt.scatter(x,y)
plt.setp(plot.axes.get_xticklabels(), visible=False)
plt.setp(plot.axes.get_xticklabels()[::5], visible=True)

The above does every 5th label; change it to whatever you need.


This answer was posted as an edit to the question How do I display only every nth axis label by the OP PiotrChernin under CC BY-SA 4.0.

vvvvv
  • 25,404
  • 19
  • 49
  • 81