3

I'm having a slightly frustrating situation with pandas/matplotlib (not sure which one's at fault here). If I create a simple random series and plot it as a line chart, the formatting is pretty clean:

test1 = pd.Series(index = pd.date_range(start='2000-06-30', end='2018-06-30', freq='3M'),
                 data = np.random.rand(73))
test1.plot(kind='line')

Most satisfactory. If I change the format to bar, though, the x-axis formatting goes to hell in a handbasket:

enter image description here

Matplotlib seems to feel obliged to label every single bar. Is there a logical reason for this or an easy fix?

Thanks in advance.

Chris Harris
  • 177
  • 3
  • 9
  • 1
    By plotting as bars, you're changing a continuous variable (time) to a discrete variable. Matplotlib is just doing what you asked it to do, which is to represent each time unit as its own bar - it's no longer a continuum, as far as the graph is concerned, so it doesn't have any intuition for how to summarize the span of the x axis (since there's no span, just categories now). – andrew_reece Jul 25 '18 at 00:45
  • See [this answer](https://stackoverflow.com/a/49714879/2799941) for your solution. Just set `ax = test1.plot(kind='bar')` to make the answer work in your case. – andrew_reece Jul 25 '18 at 00:48
  • @andrew_reece: Thanks - that does give some clarification on its behaviour. – Chris Harris Jul 25 '18 at 02:55

1 Answers1

2

Matplotlib is trying to use each time as its own bar, and is trying to label each bar appropriately. To change this behaviour, you should change the xticks or the xticklabels. For example, one quick way to just remove the labels entirely is to do something like

subplot = test1.plot(kind='bar')
ax = subplot.axes
#ax.set_xticks([])       # Alternatively, you can manually adjust the ticks
ax.set_xticklabels([])   # or their labels
f = ax.get_figure()
f.show()

which will produce

A plot with no tick labels

You can reduce the number of ticks to something like using every nth tick and its label in the same way.

davidlowryduda
  • 2,404
  • 1
  • 25
  • 29