Matplotlib Import fails after successive run of custom tool

562
6
08-16-2018 08:33 AM
JoshStreufert
New Contributor II

Hey all - I have a custom toolbox that imports Matplotlib and numpy to do some charting.  The tool will run perfect upon opening and on an initial run.  Each successive run in an open ArcMap session gives me the error: import matplotlib as plt KeyError: u'PolyCollection'

Any ideas or help is appreciated!

0 Kudos
6 Replies
DarrenWiens2
MVP Honored Contributor

I can't explain your situation, but I will point out that it is by far more common to see the following, so I suggest sticking to that for compatibility:

import matplotlib.pyplot as plt
JoshStreufert
New Contributor II

Thanks Darren - I did have that at the top of my script.  I'm not entirely sure how to proceed without abandoning the matplotlib library.

0 Kudos
DarrenWiens2
MVP Honored Contributor

I might be barking up the wrong tree, but can you confirm you don't have both of these in your script?

import matplotlib.pyplot as plt
import matplotlib as plt

Perhaps more usefully, can you post the script you do have?

0 Kudos
JoshStreufert
New Contributor II

Here are my import statements...

Like I said, runs fine the first time but subsequent times python throws an error like it cant load the library.

import arcpy
import os
import datetime
import exceptions, sys, traceback
import matplotlib.pyplot as plt
import numpy as np
import math‍‍‍‍‍‍‍‍
0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

You might want to have a look at the variables you are using in your script... one may be overwriting a previously established namespace.  Modules are only reloaded if needed and if the namespace isn't claimed.  

I don't know what version of python you are using but check for 'reload' in python 2 and the importlib reload module in python 3.  If the namespace isn't the problem, then reload the modules at the end of the script.

Also, import numpy before matplotlib because matplotlib doesn't import the whole numpy module and you want numpy's namespace to be claimed before anything else tries to claim it

0 Kudos
SilasFrantz
New Contributor

I came across this problem writing a custom tool for ArcGIS 10.6 and distilled it to the two lines below.

import matplotlib.pyplot as plt

plt.figure()

When run from ArcMap, this would succeed the first time then error on subsequent attempts to import the module...

  File "C:\Python27\ArcGIS10.6\lib\site-packages\matplotlib\quiver.py", line 171, in <module>

    """ % docstring.interpd.params

KeyError: u'PolyCollection'

Ended up solving by repairing matplotlib using the ArcGIS Setup wizard. Not sure what may have been the cause.

0 Kudos