"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Fix the \"no display name and no $DISPLAY environment variable\" Error in Matplotlib?

How to Fix the \"no display name and no $DISPLAY environment variable\" Error in Matplotlib?

Published on 2024-11-05
Browse:370

How to Fix the \

"_tkinter.TclError: no display name and no $DISPLAY environment variable"

This error typically occurs when running a Python script using Matplotlib on a server without a graphical display. Matplotlib relies on a backend to render plots, and by default, it chooses the Xwindows backend, which requires a graphical display.

To resolve this issue, you need to instruct Matplotlib to use a non-interactive backend, such as Agg. Here's how you can achieve that:

  • Add the following code at the beginning of your script, before importing pyplot:
import matplotlib
matplotlib.use('Agg')

This code sets the matplotlib backend to Agg, which is suitable for generating static images without a display.

  • Alternatively, you can add the following line to your .config/matplotlib/matplotlibrc file:
backend: Agg

This will permanently use the Agg backend for your Python scripts.

  • If you are connecting to the server remotely, use the following command:
ssh -X remoteMachine.com

This command will enable X11 forwarding, allowing you to use a display on the server.

  • You can also try exporting the DISPLAY variable:
export DISPLAY=mymachine.com:0.0

This will set the DISPLAY environment variable, which is required for the Xwindows backend.

For more information on using Matplotlib on servers, refer to the documentation: https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server

Release Statement This article is reprinted at: 1729601116 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3