Alena
Alena

Reputation: 15

How to plot piecewise constant function in python

I am trying to plot a uniform distribution having x and y values. So the function looks like in this pictureenter image description here

I need to plot this piecewise function in python, so I have tried to do it like shown below:

y = np.array([0, 0.04, 0.12, 0.16, 0.28, 0.32, 0.36, 0.44, 0.48, 0.52, 0.56, 0.72, 0.76, 0.8, 0.88, 0.92, 1])
x = np.array([0, 1, 4, 5, 6, 7, 8, 9, 11, 12, 14, 15, 17, 19, 21, 23, 24 ])

fig, ax = plt.subplots(figsize=(6, 4))
ax.hlines(y=y, xmin=0, xmax=x, color='r', linestyles='--')
plt.plot(x,y)
ax.margins(x=0)
ax.set_yticks(y, [f'{yi:.2f}' for yi in y])
plt.show()

And it gives me enter image description here

However I need this plot to look like ‘steps’:enter image description here

Does anyone know how to optimize my code?

Upvotes: 0

Views: 96

Answers (0)

Related Questions