'matplotlib.show() seemingly not doing anything
I'm trying to get a simple python program to show a graph. I'm running Python 3.9 on Mac Catalina. My code is:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1,120,120)
y = (2*10**-5)**2 + ((0.001)/(x))**2
plt.plot(x, y)
plt.show()
I've tried following the instructions laid out in this: matplotlib hangs on mac osx and graph is not displayed
Namely, changing Interactive: False to Interactive: True in the matplotlibrc file, which didn't make any difference, and replacing:
import matplotlib.pyplot as plt
with the following:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
But that hasn't worked either (I checked to see if the graph had gotten lost behind my terminal or anywhere else, and I couldn't find it so I'm assuming it hasn't showed).
In my matplotlibrc file, it has backend: Agg, but when I type matplotlib.get_backend() into my terminal whilst running Python, it returns "MacOSX". Given what it says in the matplotlibrc,
## ***************************************************************************
## * BACKENDS *
## ***************************************************************************
## The default backend. If you omit this parameter, the first working
## backend from the following list is used:
## MacOSX Qt5Agg Gtk3Agg TkAgg WxAgg Agg
## Other choices include:
## Qt5Cairo GTK3Cairo TkCairo WxCairo Cairo
## Qt4Agg Qt4Cairo Wx # deprecated.
## PS PDF SVG Template
## You can also deploy your own backend outside of matplotlib by referring to
## the module name (which must be in the PYTHONPATH) as 'module://my_backend'.
#backend: Agg
should this not be returning "Agg"?
I downloaded both numpy and matplotlib using pip3, and I'd prefer not to use Anaconda if possible, as I seem to have messed up my Windows machine installing and uninstalling there, but that is part of a different question.
When I copy and paste my code directly into the terminal running Python, my graph shows, which I suppose solves the problem of my graph not showing, but then I still have the problem if I want to run longer pieces of code, which would be my next step, as I eventually want to import a graph from matlab and compare it to this plot.
If I change my code to include the solution from the link above, so that my code reads:
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
print(matplotlib.get_backend())
import matplotlib.pyplot as plt
x = np.linspace(1,120,120)
y = (2*10**-5)**2 + ((0.001)/(x))**2
plt.plot(x, y)
plt.show()
It outputs TkAgg, but then still doesn't show my graph. Why is this happening, and what can I do to fix it so that I can make graphs without copying and pasting into the terminal?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
