0

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?

5
  • 2
    The function you need is plt.step() Commented Mar 21, 2024 at 14:00
  • 3
    Better yet, ax.step(): don't mix the pyplot and the object-oriented interface. Commented Mar 21, 2024 at 14:01
  • I am not sure that I understand how to use it. Can you please add a code comment? Commented Mar 21, 2024 at 15:14
  • 1
    Pretty sure you can can substitute plt.plot(...) with ax.step(...) and it should work. See matplotlib.org/stable/gallery/lines_bars_and_markers/… Commented Mar 21, 2024 at 15:31
  • Does this answer your question? How do I plot a step function? Commented Mar 21, 2024 at 17:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.