Skip to main content

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

| 09.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):
    import matplotlib.pyplot as plt
    import os
    plt.ylabel(‘hello [unit]’)
    plt.xlabel(‘kitty [unit]’)
    wd = solution.Parent.WorkingDir
    myPath = os.path.join(wd,’myFig.png’)
    image = solution.AddImage(myPath)

  • Right click on your Python Code object and Connect

Connect Python Code Object
Connect Python Code Object
  • Resolve your model.

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

Simple Plot
Simple Plot

The plot is also saved to the working directory.