0

I has run the following code by VSCode:

import numpy as np
import matplotlib.pyplot as plt 

a = np.array([2, 4, 5])
plt.plot(a)
print('Hello')

Its output didn't show matplotlib figure but still print 'Hello'. This is output log:

Unable to init server: Could not connect: Connection refused
Unable to init server: Could not connect: Connection refused

(demo.py:16992): Gdk-CRITICAL **: 10:33:28.827: gdk_cursor_new_for_display: assertion 'GDK_IS_DISPLAY (display)' failed
Hello

I run this code by VSCode, Ubuntu 20.04. But when I run by Spyder3, It shows the figure normally.

Tung Ng.
  • 1,241
  • 2
  • 8
  • 12

1 Answers1

3

I don't know VSCode but I guess that it does not make use of more sophisticated (Qt) consoles which can display matplotlib figures. This is the case for Spyder if I remember correctly.

Quick matplotlib intro:

  • Actually your graph is plotted but not shown
  • Usually you can display your plot in a separate window with plt.show(). Then the console is "locked". By closing the window you "delete" your plot. So new "lines" (e.g. plt.plot(a+1)) will be plotted in a new window without your previous data.
  • You can start the interactive mode by calling plt.ion() (deactive with plt.ioff()). Then plt.show() does not lock your console
  • Instead of plotting you can save it directly with plt.savefig("filename.png"). Perhaps you want to set the backend and prevent it from loading the GTK stuff. Then you don't get the Gdk-CRITICAL message. Insert import matplotlib; matplotlib.use('Agg') before you import pyplot

Does it solve your problem?

If not it may be helpful to answer the following:

  • What happends when you change your (interactive) backend? Tip: read the help help(matplotlib.use) (of course after loading import matplotlib)

  • What is your default backend? matplotlib.get_backend()

Daniel
  • 141
  • 1
  • 10
  • I was already saving to a file, but the suggestion of adding matplotlib.use('agg') removed the warning. As the post indicates, it must be done before importing pyplot. – J.O.L. Oct 02 '21 at 03:16