Home > Blockchain >  How to draw a vertical line with double left click while using blitting in matplotlib?
How to draw a vertical line with double left click while using blitting in matplotlib?

Time:05-16

I'm trying to write a program which would let user to create vertical line on the chart in the place of double left click. Actually I already can write this kind of program but now I need to add blitting to it. So I wrote below code and it doesn't work. Can someone tell me how to fix this?

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot()

plt.pause(0.1)

bg = fig.canvas.copy_from_bbox(fig.bbox)
fig.canvas.blit(fig.bbox)

def dbl_lmb_to_create_a_line(event):
    if event.button == plt.MouseButton.LEFT and event.dblclick == True:
        line = ax.axvline(event.xdata)
        ax.draw_artist(line)

dbl_lmb_to_create_a_line_connector = fig.canvas.mpl_connect("button_press_event", dbl_lmb_to_create_a_line)

while True:
    fig.canvas.restore_region(bg)
    fig.canvas.blit(fig.bbox)
    fig.canvas.flush_events()

CodePudding user response:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot()

plt.pause(0.1)

bg = fig.canvas.copy_from_bbox(fig.bbox)
fig.canvas.blit(fig.bbox)


def dbl_lmb_to_create_a_line(event):
    if event.button == plt.MouseButton.LEFT and event.dblclick:
        line = ax.axvline(event.xdata)
        ax.draw_artist(line)
    plt.show()


dbl_lmb_to_create_a_line_connector = fig.canvas.mpl_connect("button_press_event", dbl_lmb_to_create_a_line)

while True:
    fig.canvas.restore_region(bg)
    fig.canvas.blit(fig.bbox)
    fig.canvas.flush_events()

Adding plt.show() at the end of the function will do

CodePudding user response:

I found solution - adding a for-loop which draws all lines added to canvas is the thing.

while True:
    fig.canvas.restore_region(bg)
    for i in range(0,len(ax.get_lines())):
        ax.draw_artist(ax.get_lines()[i])
    fig.canvas.blit(fig.bbox)
    fig.canvas.flush_events()
  • Related