user14375170
user14375170

Reputation:

How to make bars in bar charts fill all the gaps

I have a problem with matplotlib.pyplot.bar in which bars can have only constant width, but I want to make a plot, where bars are located between two points. As we can see in the figure, points have different distances, and I want to fill all the gaps with bars. Sorry if this was asked before, I couldn't find it.

enter image description here

so basically I want to bar of the point I have a width of the distance between i and i+1, if that makes any sense.

Upvotes: 0

Views: 338

Answers (1)

JohanC
JohanC

Reputation: 80509

The following example creates a bar plot with 7 height values and 8 boundaries. The difference between successive boundaries is used as the bar widths. Bars are default aligned with their centers, but when working with uneven widths, align='edge' is needed.

from matplotlib import pyplot as plt
import numpy as np

bounds = np.array([21000, 31000, 41000, 53000, 62000, 73000, 81000, 90000])
heights = np.random.randint(50000, 120000, len(bounds) - 1)

plt.bar(bounds[:-1], heights, width=np.diff(bounds), align='edge', color='crimson', ec='navy')
# plt.xticks(bounds) # to have the boundaries as x ticks
plt.show()

example plot

Upvotes: 2

Related Questions