Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot a line with rectangular interpolation in matplotlib [duplicate]

I want to plot data, where consecutive points are connected by parts of a rectangle, either flat then vertical, or vertical then flat. Here's a naive way to do it:

import matplotlib.pyplot as plt

x_data = [0.0, 1.0, 3.0, 4.5, 7.0]
y_data = [1.5, 3.5, 6.0, 2.0, 9.0]

# Linear interpolation
plt.plot(x_data, y_data, label='linear_interp')

# Vertical first interpolation
x_data_vert_first = [0.0, 0.0, 1.0, 1.0, 3.0, 3.0, 4.5, 4.5, 7.0]
y_data_vert_first = [1.5, 3.5, 3.5, 6.0, 6.0, 2.0, 2.0, 9.0, 9.0]
plt.plot(x_data_vert_first, y_data_vert_first, label="vert_first")

# Horizontal first interpolation
x_data_flat_first = [0.0, 1.0, 1.0, 3.0, 3.0, 4.5, 4.5, 7.0, 7.0]
y_data_flat_first = [1.5, 1.5, 3.5, 3.5, 6.0, 6.0, 2.0, 2.0, 9.0]
plt.plot(x_data_flat_first, y_data_flat_first, label="flat_first")

plt.legend(loc='upper left')
plt.show()

Interpolation Comparison

Are there any pyplot options that achieve this? Built in interpolation functionality in numpy or scipy? I haven't seen any in the documentation (eg this is not a box or bar plot, but different)

I could write a naive function to do this type of interpolation for me, but I'd rather stick to library stuff if possible.

like image 472
ijustlovemath Avatar asked Nov 06 '25 16:11

ijustlovemath


1 Answers

You can use plt.step to get the same result:

plt.plot(x_data, y_data, label='linear_interp')
plt.step(x_data, y_data, where = 'pre', label = 'vert_first')
plt.step(x_data, y_data, where = 'post', label = 'flat_first')
plt.legend(loc='upper left')
plt.show()
like image 173
sacuL Avatar answered Nov 09 '25 04:11

sacuL



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!