简体   繁体   中英

python plot horizontal line for a range of values

I am really new to python and trying to plot speed as a constant value for the distince from its current startpointinmeters to the next startpointinmeters, so speed is constant from the start to the end (next start).

For example, speed should be 13 for distance 0 to 27.82 and 15 from 27.82 to 40.12 and so on.

Any idea?

startpointinmeters speed
0.0     13.0
27.82   15.0
40.12   14.0
75.33   14.0
172.77  17.0
208.64  18.0
253.0   21.0
335.21  20.0
351.16  25.0
590.38  22.0
779.37  21.0
968.35  22.0
1220.66 20.0
1299.17 19.0
1318.32 14.0
1352.7  9.0

This can be done with the step function of Matplotlib:

import matplotlib.pyplot as plt

x = [0., 27.82, 40.12, 75.33, 172.77, 208.64, 253., 335.21, 351.16,
     590.38, 779.37, 968.35, 1220.66, 1299.17, 1318.32, 1352.7]
v = [13., 15., 14., 14., 17., 18., 21., 20., 25., 22., 21., 22., 20., 
     19., 14., 9.] 

plt.step(x, v, where='post')
plt.xlabel('Position [m]')
plt.ylabel('Speed [m/s]')
plt.show()

Result:

在此输入图像描述

See this example for the difference between the different values for the 'where' argument. From your description it seems you want the 'post' option.

You need to plot the points (0.0, 13.0), (27.82,13.0), (27.82,15.0), (40.12,15.0)... and continue like that till the end.

When you plot a line between (0.0, 13.0) and (27.82, 13.0) it will draw a flat line between 0 and 27.82, at the level of 13.0. Then, when the next point comes, the line goes from (27.82, 13.0) to (27.82, 15.0), meaning it goes up without going anywhere in the x axis. And so on.

In other words, you need to do a loop through all the values xi and yi, and pair them like: (x[i], y[i]), (x[i+1], y[i]) and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM