5

I am trying to use DataFrame.plot.bar() to plot a Series of data.

plot = myData.plot.bar()

However, there are a lot of data so the Xaxis are overlapping each other.

I am looking for a way to just show nth xlabel while keep all my current data

what i have tried: I have read through axes documentation and found some useful function.

My attempt:

ticks = plot.get_xticks()
for tick in ticks:
    if tick%5 != 0:
        tick.set_visible(False)

Problem: get_xticks() returns locations, not actual ticks. So set_visible will result in error.

What i need help for: Is this a right approach to show every nth xlabel? If so, I already have the location, how can I get the actual tick so i can set the visibility of each.

If this is not the right approach, then what is the correct way of doing so?

Community
  • 1
  • 1
ZpfSysn
  • 807
  • 2
  • 12
  • 30

2 Answers2

11

If you are just trying to turn off the tick labels, you can do so by enumerating the .get_xticklabels() and turning off visibility for the ones you want to hide.

import pandas as pd
import numpy as np
x = np.linspace(100, 500, 51, dtype=int)

mydata = pd.DataFrame({'A': np.histogram(np.random.normal(300, 100, 500), bins=x)[0]},
    index=x[:-1])

ax = mydata.plot.bar()

This is the graph produced enter image description here

To change the x-axis labels, so only 1 in 5 show, use enumerate rather than the value of the label position to determine if it should be shown or not.

for i, t in enumerate(ax.get_xticklabels()):
    if (i % 5) != 0:
        t.set_visible(False)

Which produces this plot: enter image description here

James
  • 32,991
  • 4
  • 47
  • 70
1

Try xaxis.get_major_ticks() instead:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    'name':['john','mary','peter','jeff','bill','lisa','jose'],
    'age':[23,78,22,19,45,33,20]
})

ax = df.plot(kind='bar',x='name',y='age')
xticks = ax.xaxis.get_major_ticks()
for i,tick in enumerate(xticks):
    if i%5 != 0:
        tick.label1.set_visible(False)

plt.show()
Heath Raftery
  • 3,643
  • 17
  • 34