Matplotlib: bar/bin style plot of a piecewise constant function

Viewed 48

I want to make a demonstration for the approximation of an integral of a continuous function with piecewise constant step functions.

The resulting plot should look something like this:

enter image description here

I have the piece constant function, my problem is that I don't know how to plot it since the typical candidates don't seem to work:

It looks similar to a histogram, but is generated very differently.

And from what I have seen bar-charts don't align to the number line.

The plt.step() method on the other hand does not include the bins/bars; using it I got this so far: enter image description here

with this code

kwargs = dict(drawstyle = 'steps-mid')

plt.plot(times, f(times),  '-')
plt.plot(times, fitted_values, **kwargs)

Is there a dedicated function, or some kwargs argument that I overlooked, that can plot what I need here?

Edit: Thank you for the answer @Stef ! I just tried this solution and recognized an issue with a bar-plot here. plt generates a bar for every value in the times array. Now I get this result: enter image description here

1 Answers

You can use bar with the align parameter:

import numpy as np

x = np.linspace(0, 1, 11)
y = x**2 + 1
plt.plot(x, y, 'r-')
plt.bar(x, y, width=0.1, align='edge', fc='lightgreen', ec='k')
plt.xlim(0, 1)

enter image description here

Related