Python Forum

Full Version: Mathplotlib - passing reference to axs to function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have defined a series of subplots:
fig, ((ax1, ax3), (ax2, ax4), (ax5, ax7), (ax6, ax8)) = plt.subplots(4,2)
fig.subplots_adjust(left = .1, right = 1., bottom = .1, \
                    top = .9, wspace = .2, hspace = .5)
For several of these axes, I want to place vertical lines at events specified in a dictionary:
for ev in majorEvents.values():
    ax1.axvline(ev[6], ev[1], ev[2], color = ev[3], linestyle = ev[4],\
                marker = ev[5], label = ev[0])
In this case it was ax1. But I want to do this in several of the axes. I can certainly replicate this short code where I need it, but I would like to create a function that would do this for me. All I would have to do is pass the axes indicator: ax1, ax3, etc.

So the function I have is:
def showEvents(plotID):
    for ev in majorEvents.values():
        eval(plotID + '.axvlines(ev[6], ev[1], ev[2], color = ev[3], \
             linestyle = ev[4], marker = ev[5], label = ev[0])')
When I call the function,
showEvents('ax1') 
i get the following:
Error:
File "/Users/me/Python/Umbrella/umbrella.py", line 463, in <module> showEvents("ax1") File "/Users/me/Python/Umbrella/umbrella.py", line 122, in showEvents eval(plotID + '.axvlines(ev[6], ev[1], ev[2], color = ev[3], \ File "<string>", line 1, in <module> AttributeError: 'AxesSubplot' object has no attribute 'axvlines'
So passing a string with the reference to the axes to the function and then concatenating and evaluating the resultant does not work.

Not sure where to go from here.

Any suggests would be greatly appreciated.
So plotID is passed to the function, but where does the function get axvlines? Probably need to pass that too.
Why are you using eval?

def showEvents(ax, events):
    for ev in events.values():
        ax.axvlines(ev[6], ev[1], ev[2], color = ev[3], \
             linestyle = ev[4], marker = ev[5], label = ev[0])[

showEvents(ax1, majorEvents)
Dean

I had previously tried what you are suggesting:

def showEvents(ax, events):
    for ev in events.values():
        ax.axvlines(ev[6], ev[1], ev[2], color = ev[3], \
             linestyle = ev[4], marker = ev[5], label = ev[0])
and then call it as
showEvents(ax1, allEvents)
and receive the error
Error:
ax.axvlines(ev[6], ev[1], ev[2], color = ev[3], \ AttributeError: 'AxesSubplot' object has no attribute 'axvlines'
I had hoped that doing the eval of the concatenation would resolve the issue. But it does not.
Try axvline, not axvlines.
Why didn't I catch that before??!! Thanks