0

My code is :

  1 import matplotlib
  2 matplotlib.use('Agg')
  3 import matplotlib.pyplot as plt
  4 def main():
  5    
  6     
  7     dataX = [1,2,3,4]
  8     dataY = [1,2,3,1]
  9     plt.plot(dataX,dataY)
 10     plt.title("pic")
 11     plt.xlabel("x")
 12     plt.ylabel("y")
 13     plt.show()
 14 if __name__ == "__main__":
 15     main()

The code can run successfully, but no graph pops up. Earlier, I didn't use matplotlib.use('Agg') and just import matplotlib.pyplot as plt then, I got the error ImportError: Gtk* backend requires pygtk to be installed. I tried many ways on StackOverflow, but all doesn't work. The error info shows: enter image description here

2
  • 3
    The 'Agg' backend cannot show any figure (you can still save it though). In order to show the figure you need to use any of the interactive backends. The error you get can be taken literally. If you want to use the GTK3Agg backend, you need to install pygtk. Commented Apr 10, 2020 at 19:56
  • Yes, I've tried Qt5Agg ,Qt4Agg and something like these, and then I got error ValueError: Unrecognized backend string I have run pip install pygtk Commented Apr 10, 2020 at 20:06

1 Answer 1

1

If you want to get a figure in the console:

import tkinter
import matplotlib.pyplot as plt

def main():  
    dataX = [1,2,3,4]
    dataY = [1,2,3,1]
    plt.plot(dataX,dataY)
    plt.title("pic")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.show()
if __name__ == "__main__":
    main()

You can also try to save a figure:

def main():  
    dataX = [1,2,3,4]
    dataY = [1,2,3,1]
    plt.plot(dataX,dataY)
    plt.title("pic")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.savefig("figure.png")
    plt.show()
Sign up to request clarification or add additional context in comments.

6 Comments

There is still no graph pops up, but save figure is worked.
Tkinter must be installed and should not be the first two lines ("import matplotlib" and "matplotlib.use('Agg')") What is the error information?
There is no error when I use python3, but it doesn't have a graph showing up. My python version is 2.7.5.
I use python 3.7.3 and this code is workking correctly.
As mentioned by Ernest, pygtk needs to be installed. Also note that plt.savefig needs to be called before plt.show because plt.show typically erases the plot.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.