-2

I have a data, which contains values for each day of January:

self.y_data:  [0, 0, -4, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

matplotlib bar chart uses this self.y_data to set y values for each day. But I get the following chart:

enter image description here

Why only 4 values are shown in the graph? How do I display all 31 values?

alwbtc
  • 28,057
  • 62
  • 134
  • 188

1 Answers1

2

It seems that the x axis range is not set to include the points where the data is zero. One workaround is simply to explicitly set the x limit according to the data.

import matplotlib.pyplot as plt 

y  = [0, 0, -4, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0]
x = xrange(len(y))

fig, ax = plt.subplots(1, 2)
# show with default limits
h0 = ax[0].bar(x, y)
# same data, but explicitly set x range
h1 = ax[1].bar(x, y)
ax[1].set_xlim(x[0], x[-1]+1)

plt.show()

bar charts with different ranges

Note: this matplotlib forum post also describes a similar issue.

(I had to guess where your x values come from but the principle is shown)

Bonlenfum
  • 19,101
  • 2
  • 53
  • 56
  • Sir, thank you. I will try your suggestion. But how about `self.axes.set_xbound(lower=0, upper=len(self.y_data))` ? what is the difference between `set_xbound` and `set_xlim`? – alwbtc Mar 07 '14 at 14:01
  • I also noticed that `upper` and `lower` are not arguments of `set_xlim`. We should use `left` and `right` instead. – alwbtc Mar 07 '14 at 14:09
  • I didn't know about `set_xbound`; but http://stackoverflow.com/q/11459672/1643946 suggests that the limits are static while the bounds can be automatically updated (e.g. when adding more data to a graph that was outside the previous range). – Bonlenfum Mar 07 '14 at 14:39
  • Look at the code, https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_base.py#L2424, `set_xbound` allows you to set the limits in a way that will not change the axis inversion (do positive numbers increase to the left or to the right).\ – tacaswell Mar 07 '14 at 16:27