4

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.

0

1 Answer 1

7

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()
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I was missing, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.