Compatibility issue between python-ovito library and matplotlib

Hello

I am using Python version 3.10.5, matplotlib version 3.8.0, and ovito version 3.9.2 on a Windows 10 operating system.

I am running the simplified code provided below:

def main():
    import numpy as np
    import ovito
    import matplotlib.pyplot as plt

    data = np.random.random((10, 2))
    plt.plot(data[:, 0], data[:, 1])
    plt.show()

main()

I encountered the following error:
QWidget: Cannot create a QWidget without QApplication

When I remove the statement import ovito, the code runs successfully and plots the graph.
I am not using conda. Could you please let me know if this is a compatibility issue between ovito and matplotlib or if I need to install other dependencies? I couldn’t find any relevant information in the ovito manual.

Thank you in advance.

Matplot uses the QtAgg backend by default to display plotting windows. That backend is based the Qt cross-platform GUI framework. OVITO too uses the Qt framework internally.

The Qt framework relies on the creation of a global “application” object, which exists in two flavors: a GUI-based application object and a non-GUI one (used in terminal programs). Only a single global application object can exist at a time. The OVITO module creates a non-GUI object during import. Matplotlib’s QtAgg backend, however, requires a GUI application object (which it cannot create anymore, because of the already existing app object from OVITO). That’s why you are getting the error message.

Solution:

You can request OVITO to create a GUI application object by setting the environment variable OVITO_GUI_MODE=1 before importing the module. Then OVITO and Matplotlib will share the same application object:

import os
os.environ['OVITO_GUI_MODE'] = '1'
import ovito
import matplotlib.pyplot as plt

The environment variable OVITO_GUI_MODE is documented here: ovito.vis — OVITO Python Reference 3.9.2 documentation