Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When plotting, wanting to 'hold' a y value over an x interval. [Not a 'bar plot' question]

For some reason I am blank on this one:

x = np.arange(5)
[0 1 2 3 4]

y = np.array((3, 6, 1, 9))
[3 6 1 9]

plt.plot(???)

What to do with the arrays so that a plot will hold constant over a 'bin' of 0 to 1. i.e the value 3 between the interval 0 to 1, the hold the value 6 between 1 to 2 and so on.

This is a concept example because my real problem is that I am making a Spectrogram from scratch and am using plt.pcolormesh(X, Y, Z). I have arrays in similar fashion to this example and the size is not matching. Either I have to stop using the number 0 or number 4 to match but then the matching is wrong by 1 datapoint in respective direction.

like image 255
Mashhood Ahmad Avatar asked Oct 30 '25 07:10

Mashhood Ahmad


1 Answers

You would need to append the last y point, such that both arrays have the same number of elements, then use drawstyle="steps-post" to get a step-like appearance.

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(5)
#[0 1 2 3 4]

y = np.array((3, 6, 1, 9))
#[3 6 1 9]

plt.plot(x, np.concatenate((y, [y[-1]])), drawstyle="steps-post")
plt.show()

enter image description here

Note that this is unrelated to plt.pcolormesh(X, Y, Z), where Z can (or should even) have one element less than the grid in each direction.

like image 189
ImportanceOfBeingErnest Avatar answered Nov 01 '25 21:11

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!