-1

I know What is the difference between importing matplotlib and matplotlib.pyplot? is similar. But according to what Plasma commented there it should be able to write from matplotlib import * and then matplotlib.pyplot.plot . But as you can see I am only getting NameError. I know you can write from matplotlib import pyplot. But I only want to know why you cannot write like the picture of the program below:

Why does this not work

Thanks in advance!

8
  • 2
    Because you are not importing matplotlib, but all the elements of matplotlib; basically the object matplotlib is not in the environment, but the children objects are. Commented Nov 10, 2020 at 14:11
  • BigBen - I tried that but it does not work for me. Commented Nov 10, 2020 at 14:15
  • But when I write from matplotlib import *, isn't then pyplot just one out of the many modules that I am importing. So from matplotlib import pyplot should just be one of the modules that * refers to, right? Commented Nov 10, 2020 at 14:21
  • Also, how do I access pyplot if I would only write import matplotlib at the start of the program? Commented Nov 10, 2020 at 14:24
  • BigBen - But what if I wanted to use several of the functions that matplotlib offers. I suppose I would write import matplotlib or from matplotlib import *. But how would I access specific functions like plot() from pyplot and so on? Commented Nov 10, 2020 at 14:30

1 Answer 1

2

Simply put, pyplot is a submodule of matplotlib which will not automatically be imported just because you import matplotlib.

When you run import matplotlib as mpl, only a specific set of methods will be imported, i.e. you could use mpl.use() or mpl.rc_params afterwards. If you are interested in what exactly is available to you after importing, try:

print(dir(mpl))

When you run from matplotlib import *, the same methods as before are available, just without the mpl. prefix. That's why you should usually not do this, as you may have planned to write your own function called use().

If you want to actually plot, you'll need to import pyplot explicitly, i.e add either:

from matplotlib import pyplot

or:

import matplotlib.pyplot as plt

Important sidenote: importing matplotlib.pyplot actually further populates the mpl namespace; only when importing both matplotlib as mpl as well as matplotlib.pyplot, you'll get access to the mpl.ticker module. If you don't import pyplot explicitly, you'll get an AttributeError: "module 'matplotlib' has no attribute 'ticker'"

Suggested reading regarding the use of namespaces in python

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.