M15onebillion
M15onebillion

Reputation: 13

Drawing on top of an existing graph Python Matplotlib

So I'm writing a program using matplotlib in order to initially plot a basic graph and then put points on it. What I was aiming to do was to place the mouse on a certain point in the graph and click in order to add points. I can't seem to find any resources which clearly states how to actually input point as the event of clicking the mouse happens after the initial graph is plotted. Here is what I have so far.

import matplotlib.pyplot as plt
import numpy as npy
x,y,vx,vy=npy.loadtxt('issmplotdat.txt',delimiter=',',unpack=True)
elements=npy.loadtxt('issmplotdatelements.txt',delimiter=',')

vel=npy.sqrt(vx**2+vy**2)

fig = plt.figure()
plt.tricontourf(x,y,elements,vel)
plt.hold(True)
plt.plot(3,9, 'ro')

def on_keyboard(event):
    print "you pressed", event.key, "\nat:", event.xdata, event.ydata
    plt.plot(9, 9, 'ro')
    print "plotted"

def on_click(event):
    print('ehllo')
    print 'you pressed:', event.button, '\nat:', event.xdata, event.ydata
    plt.plot(event.xdata, event.ydata, 'ro')


zing = fig.canvas.mpl_connect('button_press_event', on_click)
ding = fig.canvas.mpl_connect('key_press_event', on_keyboard)

plt.show()

Many thanks in advance!

-MS

Upvotes: 1

Views: 2039

Answers (1)

Raghav RV
Raghav RV

Reputation: 4076

You need to update the plot by calling figure.canvas.draw() after you have called the plot function.

[ Note that for doing so you need to access the global fig variable ]

So in your case, the on_click callback function would be :

def on_click(event):
    plt.plot(event.xdata, event.ydata, 'ro')
    global fig
    fig.canvas.draw()

enter image description here

Upvotes: 1

Related Questions