简体   繁体   中英

Draw and distribute vertical lines with matplotlib

I have created a code that allows me to draw straight lines by coordinates from a 'input_draw' list, on which arrows are placed in a downward direction for each unit of the plot (space=1) .

import matplotlib.pyplot as plt 

input_draw = [[6, 'Row',    0, 2.5, 5, 2.5,  0.42,], 
              [7, 'Row',    5, 2.5, 9, 2.5,  0.60,], 
              [8, 'Row',    0, 5.0, 5, 5.0,  0.30,]]
    
# Draw --------------------------------------------@    
fig = plt.figure()

for i in range(len(input_draw)): 

    xi = input_draw[i][2]
    yi = input_draw[i][3]
    xf = input_draw[i][4]
    yf = input_draw[i][5]
    
    wd_height = abs(input_draw[i][6])

    # This is the space where I want the arrows to be placed
    
    space = 1
    
    plt.plot((xi, xf), (yi, yf), color='blue', linewidth=4) 
    
    if abs(input_draw[i][6]) > 0:
        plt.plot((xi, xf), (yi+wd_height, yf+wd_height), color='green', linewidth=1) 
        
        plt.arrow(xi, yi+wd_height, 0, -wd_height,color='green', linewidth=1, 
                  length_includes_head=True, head_width=0.1, head_length=0.1)

plt.show() # -------------------------------------------------------------@

Is there a method to graph these arrows for each unit of the plot?

To illustrate the idea, at the moment my graph is like this:

在此处输入图像描述

But I want him to be like this.

在此处输入图像描述

Best regards.

With np.arange(start, end, step) you can create a list of all positions to draw an arrow. As np.arange works similar as range , the last position isn't included. To explictly include that last position, an epsilon (eg 1e-9 ) can be added: np.arange(start, end+1e-9, step) .

The code can be written a bit more pythonic by writing the loop as for row in input_draw instead of using indices. (Python tries to avoid the explicit use of indices whenever feasible.)

import matplotlib.pyplot as plt
import numpy as np

input_draw = [[6, 'Row', 0, 2.5, 5, 2.5, 0.42, ],
              [7, 'Row', 5, 2.5, 9, 2.5, 0.60, ],
              [8, 'Row', 0, 5.0, 5, 5.0, 0.30, ]]

for row in input_draw:
    xi, yi, xf, yf, wd_height = row[2:]
    wd_height = abs(wd_height)
    space = 1  # spacing between the arrows
    plt.plot((xi, xf), (yi, yf), color='blue', linewidth=4)
    if wd_height > 0:
        plt.plot((xi, xf), (yi + wd_height, yf + wd_height), color='green', linewidth=1)
        for xj in np.arange(xi, xf + 1e-9, space):
            plt.arrow(xj, yi + wd_height, 0, -wd_height, color='green', linewidth=1,
                      length_includes_head=True, head_width=0.1, head_length=0.1)
plt.show()

示例图

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