Home > Back-end >  plotting the stair step plot and extract continuous values
plotting the stair step plot and extract continuous values

Time:01-26

I have discrete x and y axis data as

y=[14.0,11.0,14.0,31.0]
x=[3.45,3.88,3.99,4.33]

I need to plot the figure as depicted below.

plot

Finally i want to extract continuous red line values. I tried using the code below but it doesnot give the expected result.Hope experts may help me.

import numpy as np
import matplotlib.pyplot as plt

y=[14.0,11.0,14.0,0.0]
x=[3.45,3.88,3.99,4.33]
plt.step(x,y)
plt.show()

CodePudding user response:

The first thing to notice is the x values of the step plot. Matplotlib threats these as absolute values. You also need to add the x-value 3.45 twice for the first vertical segment.

For the vertical segments there is a possibility to set it to 'pre' to draw the vertical line before the point or 'post' for after the point. I chose to set it to 'post'.

import numpy as np
import matplotlib.pyplot as plt

x = [3.45, 3.45, 3.88, 3.99, 4.33]
y = [0.00, 14.0, 25.0, 39.0, 70.0]
plt.step(x, y, 'r', label='test.mod', where='post')

# set range of x-axis
plt.xlim([2.0, 5.0])

# invert y-axis by setting the lower limit to a higher value than the upper limit 
plt.ylim([60, 0])

plt.legend()
plt.show()

CodePudding user response:

To get continuous values, use interp1d from scipy:

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

x = np.array([3.45, 3.88, 3.99, 4.33])
y = np.array([14.0, 11.0, 14.0, 31.0])
y = np.cumsum(y) # ???
y0 = np.array([0])
x0 = np.interp([0], y, x)
x = np.concatenate([x0, x])
y = np.concatenate([y0, y])

# Continuous data
NUM = 1000  # modify the number of points you want
funct = interp1d(x, y, kind='next')
x_cont = np.linspace(x[0], x[-1], NUM)
y_cont = funct(x_cont)

# Plot
fig, ax = plt.subplots()
ax.step(x_cont, y_cont, color='r', label='test.mod', where='post')
ax.set_xlim(2, 5)
ax.set_ylim(0, y.max())
ax.invert_yaxis()
plt.show()

Output:

>>> x_cont
array([3.45      , 3.54777778, 3.64555556, 3.74333333, 3.84111111,
       3.93888889, 4.03666667, 4.13444444, 4.23222222, 4.33      ])

>>> y_cont
array([ 0., 25., 25., 25., 25., 39., 70., 70., 70., 70.])

enter image description here

  • Related