1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How can I calculate a dash sequence for a line using data coordinates in matplotlib?

Discussão em 'Python' iniciado por Stack, Setembro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write a function that calculates a particular dash sequence for a line. I want to set the sequence such that the line has a single gap at a given point on the line. Below is an image of what I want. I used a hard-coded dash sequence to make it look this way.

    [​IMG]

    I think my issue is that I am not correctly converting from data coordinates to pixel coordinates. How can I calculate pixel coordinate distances for the dash sequence when I know the data coordinate distances? Below is my code and its current output.

    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    import numpy as np


    def bridge_dash_seq(ax, l, cross):

    trans = lambda x: ax.transData.transform(x)

    xl,yl = trans( np.array(l.get_data()).T ).T
    xc,yc = trans(cross)

    s = np.sqrt( (xl[0]-xc)**2 + (yl[0]-yc)**2 ) # length from first endpoint of the line to cross point
    length = np.sqrt( (xl[0]-xl[1])**2 + (yl[0]-yl[1])**2 ) # length of the line
    gap_len = length/10 # length of gap

    seq = (s-(gap_len/2), gap_len, length)

    return seq


    fig, ax = plt.subplots()

    l = Line2D((0,1), (0,2), zorder=0)
    ax.add_line(l)
    cross = (0.3, 0.6)

    ax.scatter(*l.get_data(), c='g', zorder=1)
    ax.scatter(*cross, c='r',zorder=1)

    seq = bridge_dash_seq(ax,l,cross)
    l.set_dashes(seq)


    [​IMG]

    Continue reading...

Compartilhe esta Página