Integrating images and plots using a Python Code object (Cpython)

Ansys Developer
Ansys Developer
Published in
2 min readSep 23, 2022

Today’s script tip comes from Mark Capellaro, Application Engineer at Ansys.

Python Code objects in Ansys 2022R2 allow the user to change the engine to Cypthon. This opens the door to using more modern python libraries and modules. One command python library that is now available is matplotlib, the default plotter for python. So it is already installed with your Ansys 2022R2. This functionality allows you to plot, plot to file and bring images into the Mechanical tree that might not be included natively in Mechanical.

Below is a trivial example of how to use matplotlib and a Python Code object in your Ansys Mechanical analysis. Naturally you would want to use others scripts like dpf to grab the data you want to plot.

  • In any 2022R2 Ansys Mechanical Solution right click and Insert — Python Code
  • Set the Target Callback to After Solve
  • Under Advanced, set the Engine Type to Cpython.
  • Copy and paste the script below into the Python Code window (overwrite the default text):
def after_post(this, solution):# Do not edit this lineimport matplotlib.pyplot as pltimport osplt.plot([1,2,3,4,5],[5,10,15,20,25],color=’red’)plt.ylabel(‘hello [unit]’)plt.xlabel(‘kitty [unit]’)plt.grid()wd = solution.Parent.WorkingDirmyPath = os.path.join(wd,’myFig.png’)plt.savefig(myPath)image = solution.AddImage(myPath)pass
  • Right click on your Python Code object and Connect
  • Resolve your model.

A simple plot will appear in your Mechanical Tree under the Python Code object.

The plot is also saved to the working directory.

--

--

Ansys Developer
Ansys Developer

The Ansys Developer Team writes about a variety of topics related to physics, engineering simulation, Python, AI/ML, and other developer topics.