0

I have a simple line graph, but the xticks are overlapping. Therefore I want to display only every 2nd xtick. I implemented this answer which worked for me in another graph. As you can see below it stops working after the 6th tick and I can't wrap my head around why.

My code is the following:

data = pf.cum_perc
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlabel("Days", size=18)
ax.set_ylabel("Share of reviews", size = 18)
for label in ax.xaxis.get_ticklabels()[1::2]:
    label.set_visible(False)
ax.plot(data)

pf.cum_perc is a column of a data frame (therefore a series) with the following data:

1     0.037599
2     0.089759
3     0.203477
4     0.302451
5     0.398169
6     0.486392
7     0.533514
8     0.538183
9     0.539411
10    0.550040
11    0.550716
12    0.553050
13    0.553726
14    0.654789
15    0.681084
16    0.706211
17    0.731462
18    0.756712
19    0.781594
20    0.807766
21    0.873687

(and so on)

The resulting graph: the graph

Any help is greatly appreciated :)

Janman
  • 67
  • 8
  • You need to set the labels invisible after you plotted something; else you only set the ticklabels that are present without any lineplot in the axes to invisible, not those that are created once you add the line. However, in general consider plotting numbers, not strings - this will automatically tick the axes with useful tick spacings and labels. – ImportanceOfBeingErnest Sep 07 '19 at 21:22
  • Thanks! Both solutions worked out. Do you want to formulate an answer so I can accept it? – Janman Sep 07 '19 at 21:33

1 Answers1

0

As user @ImportanceOfBeingErnest suggested:

Solution 1: Convert the x-axis data to numbers, so matplotbib takes care of the ticks automatically. In my case this is done by

pf.index = pf.index.map(int)

Solution 2: Remove the ticks, after the graph is plotted, otherwise the objects don't exist yet and therefore can't be set invisible. The new code would look like this:

data = pf.cum_perc
fig, ax = plt.subplots(figsize=(10, 6))
ax.set_xlabel("Days", size=18)
ax.set_ylabel("Share of reviews", size = 18)
ax.plot(data)

for label in ax.xaxis.get_ticklabels()[1::2]:
    label.set_visible(False)
Janman
  • 67
  • 8