Pyplot - Histogram of positive and negative values

I want the negative bars to face downward and the positive bars upward, with the x-axis (0-line) running right between them. I tried this

chart = fig.bar(x, negative_data, width=35, color='r')
ax2 = plt.gca().twinx()
ax2.bar(x, positive_data, width=35, color='b')

      

But instead, I get merged red and white stripes, both pointing down. It seems that the negative_data / positive_data arrays only indicate the height of the bar, but how do you specify the orientation? I need something to indicate the coordinates of the vertices of each bar.

Also, how do you make the width something sensible, possibly dynamic, since the graph is resized by the user?

Here's an example of the problematic width:

x = [250, 1500, 2750, 4250, 6000, 8500, 13200]
negative_data = [0, 0, 0, 0, 0, 0, 0]
positive_data = [3, 0, 0, 0, 1, 0, 0]

      

How can I make the graph of these images look nice?

+3


source to share


1 answer


You don't need to add a double axis, you can display both histograms on the same axis like this:

x = range(7)
negative_data = [-1,-4,-3,-2,-6,-2,-8]
positive_data = [4,2,3,1,4,6,7,]

fig = plt.figure()
ax = plt.subplot(111)
ax.bar(x, negative_data, width=1, color='r')
ax.bar(x, positive_data, width=1, color='b')

      



bar chart with negative an positive y values

Bars with a width of one will fill the axes and will scale to fit the shape as it changes.

+14


source







All Articles