1

I am trying to modify a plot within a mouseevent definition in matplotlib. My final endpoint is to be able to get the user to drag a greyed out area marking the starting and ending x coordinates, from which I can determine the local maxima/minima. This is where I am currently. While the first avxspan shows up in the plot, the second one doesnt. I know the mouseevent is triggered since the x,y coords are printed on console. Can someone tell me why this wouldnt work? Much appreciated.

fig=plt.figure()
plt.figure(fig.number)
plt.plot(data)
ax=plt.gca()
plt.figtext(0.25,0.92, "Calculate")
plt.figtext(0.66,0.92, "Clear")
ax.axvspan(1, 100, facecolor='0.5', alpha=0.5)

def start(event):
    global ax
    ax.axvspan(100, 200, facecolor='0.5', alpha=0.5)
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
        event.button, event.x, event.y, event.xdata, event.ydata)

cid = fig.canvas.mpl_connect('button_press_event', start)
plt.show()
fig.canvas.mpl_disconnect(cid)    

2 Answers 2

1

You might wanna take a look at the matplotlib.widgets module.

A simple one liner, enables you to drag a area, and define a callback function to get the coordinates that span the area.

simple example

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import SpanSelector

x = np.arange(10)
y = x**2

plt.plot(x,y)
ax=plt.gca()


def onselect(vmin, vmax):
    print vmin, vmax
span = SpanSelector(ax, onselect, 'horizontal')
plt.show() 
Sign up to request clarification or add additional context in comments.

1 Comment

oh shit. Have been reinventing the wheel! Thanks for pointing out to that module. I am using this hereon.
0

Call fig.canvas.draw() to update the figure:

def start(event):
    ax.axvspan(100, 200, facecolor='0.5', alpha=0.5)
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
        event.button, event.x, event.y, event.xdata, event.ydata)
    fig.canvas.draw()

3 Comments

Bow to the lord! Thanks so much for the quick and right answer:)
For those who are interested, take a look below for a one-liner code for the final endpoint that I had referred to
Well, you gave the solution to what i asked. Yes, he has given me a better approach to what i intend to do. Infact, I am using that right now. I dont want to mislead someone who is actually trying to figure out the redraw concept which I seemed to have not noticed, until now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.