简体   繁体   中英

Why matplotlib does not plot?

I started to learn MatPlotLib using this tutorial for beginners. Here is the first example.

from pylab import *
X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

If I write these 3 lines into my python file and execute it in the command line (by typing python file_name.py ), nothing happens. No error message, no plot.

Does anybody know why I do not see the plot?

ADDED

Of course I need to use show . But even if I add the following 3 lines:

plot(X,C)
plot(X,S)
show()

it still does no generate anything.

ADDED

Here are the lines that I use now:

import pylab as p
C = [1,2,3,4]
S = [10, 20, 30, 10]
p.plot(C,S)
p.show()

I still have the same result (nothing).

It could be a problem with the backend. What is the output of python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)' python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)' python -c 'import matplotlib; import matplotlib.pyplot; print(matplotlib.backends.backend)' ?

If it is the 'agg' backend, what you see is the expected behaviour as it is a non-interactive backend that does not show anything to the screen, but work with plt.savefig(...). You should switch to, eg, TkAgg or Qt4Agg to be able to use show . You can do it in the matplotlib.rc file.

@shashank: I run matplotlib both on 12.04 and 12.10 without problems. In both cases I use the Qt4Agg backend. If you don't have the matplotlibrc set, the default backend is used. I'm sure that for Precise matplotlib repo was built with TkAgg. If the Quantal version has been built with eg Agg, then that would explain the difference

You need to call the function:

show()

to be more exact:

pylab.show()

and even better don't use:

from pylab import *

rather do:

import pylab as p:

and then:

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

p.plot(C,S)
p.show()

Try adding. I use Jupyter and this worked for me.

  %matplotlib inline

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM