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
1 Answer 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
Pkzzz
There is still no graph pops up, but save figure is worked.
Alex P
Tkinter must be installed and should not be the first two lines ("import matplotlib" and "matplotlib.use('Agg')") What is the error information?
Pkzzz
There is no error when I use python3, but it doesn't have a graph showing up. My python version is 2.7.5.
Alex P
I use python 3.7.3 and this code is workking correctly.
JohanC
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. |
lang-py
'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.Qt5Agg,Qt4Aggand something like these, and then I got errorValueError: Unrecognized backend stringI have runpip install pygtk