Export multiple charts with matplotlib in ArcPro

348
2
02-03-2023 08:30 AM
ChelseaVSmith
New Contributor II

Hi I'm running a script from the python window in ArcPro 3.03 with the eventual aim of turning the script into a geoprocessing tool.

The script calculates scores for various criteria grouped in themes.  I then want to produce a chart for each theme, so six charts in total to be exported. The code works fine for one chart but when I add another after I save the first chart the script fails/crashes.

How can I export multiple charts using matplotlib in ArcPro?

# Create radar chart for Thematic Layer B
arcpy.management.SelectLayerByAttribute("AUScores", "NEW_SELECTION", "CriteriaCode LIKE 'B%'", None)
fields = ["Criteria"]
categories = [i[0] for i in arcpy.da.SearchCursor(AUScores,fields[0])]
categories = [*categories, categories[0]]
fields = ["Scores_Int"]
scores = [i[0] for i in arcpy.da.SearchCursor(AUScores,fields[0])]
scores = [*scores, scores[0]]

label_loc = np.linspace(start=0, stop=2 * np.pi, num=len(scores))

plt.figure(figsize=(9, 9))
plt.subplot(polar=True)
plt.plot(label_loc, scores, label='Score', color = 'firebrick')
plt.title('Biodiversity Values', size=20)
lines, labels = plt.thetagrids(np.degrees(label_loc), labels=categories)
plt.legend()
plt.show()
plt.savefig('BiodiversityValues.png')

#Create radar chart for Thematic Layer C
arcpy.management.SelectLayerByAttribute(AUScores, "CLEAR_SELECTION")
arcpy.management.SelectLayerByAttribute("AUScores", "NEW_SELECTION", "CriteriaCode LIKE 'C%'", None)
fields = ["Criteria"]
categories = [i[0] for i in arcpy.da.SearchCursor(AUScores,fields[0])]
categories = [*categories, categories[0]]
fields = ["Scores_Int"]
scores = [i[0] for i in arcpy.da.SearchCursor(AUScores,fields[0])]
scores = [*scores, scores[0]]

label_loc = np.linspace(start=0, stop=2 * np.pi, num=len(scores))

plt.figure(figsize=(9, 9))
plt.subplot(polar=True)
plt.plot(label_loc, scores, label='Score', color = 'firebrick')
plt.title('Human Use and Habitat Alteration', size=20)
lines, labels = plt.thetagrids(np.degrees(label_loc), labels=categories)
plt.legend()
plt.show()
plt.savefig('ImpactsAndAlteration.png')
Tags (3)
0 Kudos
2 Replies
dslamb2022
New Contributor III

Do you get a specific error output?

Instead of plt.show() I would save the figure and then close the plot before proceeding to the next figure. Also, you might need to include the full path to the output folder.

 

plt.legend()
plt.savefig(r"c:\path\figure.png")
plt.close()

 

0 Kudos
by Anonymous User
Not applicable

I'd also instantiate a new plt object for each plot instead of reusing it, del'ing it after you save it.

0 Kudos