plt.show() not working in pycharm - python-3.x

I am using pycharm after upgrading my python to python 3.5.
I re-run a standard code that i had in place and had a problem with plt.show()
example:
import matplotlib
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()
The suggestion by DavidG made things worked fine. But this time when I do
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()
i get an error saying
/apps/qtrinst/install/python/anaconda/envs/sx_anaconda/lib/python3.5/site-packages/matplotlib/__init__.py:1401: UserWarning: This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
It didnt get this error before-not sure what happened there.

I think the problem is with your "backend". The documentation has a section entitled "What is a backend?" which will be helpful.
I'm not familiar with WebAgg but I don't think you want to be using it. A more conventional one might be TkAgg which requires Tkinger or Qt4Agg which requires PyQt4. You can switch backends using
import matplotlib
matplotlib.use("TkAgg") # Do this before importing pyplot!
import matplotlib.pyplot as plt

Try using a different Backend. It worked for me when I used QtAgg
PyQt
you will need to install some version of PyQt. At the moment:
pip install PyQt6
Specify the GUI backend
import matplotlib
matplotlib.use("QtAgg")
Try plt.show()
from matplotlib import pyplot as plt
# some code here
plt.show()
This worked flawlessly for me. Hope It worked for you too.

Related

"Import as" isn't recognized, normal import is

I'm playing around with matplotlib to understand its structure better and I'm confused by the following piece of code:
import matplotlib as mpl
from mpl import pyplot as plt # ModuleNotFoundError : No module named 'mpl'
mpl.pyplot # AttributeError: module 'matplotlib' has no attribute 'pyplot'
If on the other hand I abstain from importing matplotlib as a different name and execute instead
import matplotlib
from matplotlib import pyplot as plt #works!
the things work.
Even more crazy, if I "combine" these two
import matplotlib as mpl
from matplotlib import pyplot as plt #works!
mpl.pyplot.get_backend() # works
I can curiously access attributes from pyplot even if I reference it as mpl.pyplot.
What is going on here, why does
from mpl import pyplot as plt throws a ModuleNotFoundError?
import mpl.pyplot not work? Since the error message indcates that mpl was correctly resolved to matplotlib, yet still pyplot couldn't be found...
referencing pyplot as mpl.pyplot not cause an error in my last example?
(Note that I do know of course that the preferred way is to import pyplot as import matplotlib.pyplot as plt but the point of my investigation is precisely to understand what fails and why when I ventured outside the welltrodden streets of code.)
The as part in an import statement is just syntactic sugar for assigning the imported module to a variable with the given name. The import documentation describes it as such:
If the module name is followed by as, then the name following as is bound directly to the imported module.
"Bound" in this context means doing an assignment to the given name. The following statement
import someModule as someName
Is equivalent to this code:
import someModule
someName = someModule
So, when you do import matplotlib as mpl, all you do is create a variable called mpl. This has no effect on any further import statements, as import statements do not care about your local variables, but search for python packages and modules - and an import as statement cannot change the package or module name of the imported element. Which is a good thing, as you do not want your import statements to fail just because another import 5 lines earlier used a conflicting name in an as clause.
Now, why you're getting weird results with the import mpl.pyplot statement - no idea, it shouldn't work. You can see the expected behaviour if you try the following:
import os as asdf
import asdf.path #ModuleNotFoundError: no module named 'asdf'
Tested with python 3.10.2 on Archlinux. If your example is reproducible, then you might have found a weird bug or undefined behaviour in your specific python version, or have some other issue (e.g. a mpl module in your path... although that on its own wouldn't explain why you get an error message about matplotlib instead of mpl).
In conclusion, all as does is assigning a name to the imported object, so a name assigned with as cannot be used as a source in another import statement.
On package imports and why matplotlib.pyplot gives an error:
Importing a package only imports the package itself, not any of its subpackages or modules. A package can explicitly import submodules in its __init__.py, so if the matplotlib init file would contain a statement like from . import pyplot line then accessing matplotlib.pyplot would work. There are however many reasons why a package might choose not to import any submodules, such as time and resources required to import and initialize them.
Everything in python is a object, but when you import matplotlib you are importing all library but you cannot change your functions names, the library will looking for plt
from matplotlib import pyplot as plt in this case.
You can use plt directly but you cannot use mpl.plt.
When you tried it :
import matplotlib as mpl
from mpl import pyplot as plt # ModuleNotFoundError : No module named 'mpl'
mpl.pyplot
You should import correctly:
import matplotlib as mpl
from mpl import pyplot
mpl.pyplot
'As' change the module name what you going to use in your project, but not from another import. But if you use plt directly it is going works.
Try this code to understand :
import matplotlib as mpl
import matplotlib
print(type(matplotlib))
print(type(mpl))
from matplotlib import pyplot as plt# ModuleNotFoundError : No module named 'mpl'
from matplotlib import pyplot
print(type(plt))
print(type(mpl.pyplot))
plt
mpl.pyplot
When you do import module as mdl, it doesn't change the module name. It only affects other statements when you actually use it. But the name doesn't change in the actual python lib or the external library. So what you can do is this:
import matplotlib
from matplotlib import pyplot as plt
or just from matplotlib import pyplot as plt
This is my answer...

matplotlib.plot doesn't show any image or plot without any error

I'm trying to show some images on VScode in Ubuntu, but matplotlib doesn't work. For example, even the most simple code such as:
import matplotlib.pyplot as plt
s_in = plt.imread("/media/aro/New Volume/Super resolution dataset/set5/Test/BSDS100/3096.png")
plt.imshow(s_in)
plt.show()
is not working, and it doesn't show any errors or warnings. What should I do?
In case anybody has got the same problem as mine. The error was because of the backend. So I had to change it. the only backend that worked for me was WebAgg.
Just add the following code at the beginning of your code.
import matplotlib.pyplot as plt
plt.switch_backend('WebAgg')

can anyone explain why this code regarding plotly libraries worked well in jupyter notebook but showed an error when i ran it in intellij

I saw this video on youtube : using plotting a dataframe using iplot method imported from plotly.offline module.
I ran this code on intellij but got an error saying :
latin-1' codec can't encode characters in position 0-9: ordinal not in range(256)
i looked up for a solution but couldn't anything. Then i ran this code in jupyter notebook and it worked just fine
can anyone explain this.
source code -
import pandas as pd
import numpy as np
import chart_studio.plotly as py
from plotly.offline import *
import cufflinks as cf
init_notebook_mode(connected=True)
cf.go_offline()
df=pd.DataFrame(np.random.randn(50,4),columns=['a','b','c','d'])
df.iplot()

Cannot import bokeh built in themes from bokeh.themes

I am trying to set the theme for bokeh plots on jupyter lab.
To do so I am following the official docs, copying the exact code from https://docs.bokeh.org/en/latest/docs/reference/themes.html.
However, I get an error cannot import name 'built_in_themes'.
I assume the default themes location changed, but can't seem to find anything else besides the said page documenting bokeh.themes.
I assume the default themes location changed
No, it has only ever been in the same location since it was added in version 1.0. The explanation is almost certainly that the version you are using is older than that.
As bigreddot said, same location.
Check your Bokeh version:
$ python3.7
>>> import sys
>>> print(sys.version)
>>> import bokeh
>>> print(bokeh.__version__)
Or via jupyter notebook:
import numpy as np
from bokeh.io import output_notebook, show
from bokeh.plotting import figure
Following the example here provided, the output should look like this:
Maybe you are just working in an environment with an older version.

Update a Bokeh Span with an interact element in Jupyter notebook

I am trying to make a span in bokeh using jupyter widgets.
from ipywidgets import interact
import numpy as np
from scipy.stats import norm
from bokeh.sampledata.daylight import daylight_warsaw_2013
from bokeh.io import push_notebook, show, output_notebook
from bokeh.plotting import figure
from bokeh.models import Span
output_notebook()
p = figure()
x_axis = np.arange(-10, 10, 0.001)
# Mean = 0, SD = 2.
y_axis = norm.pdf(x_axis,0,2)
p.line(x_axis, y_axis, line_dash='solid', line_width=2)
cutoff = Span(location=1,
dimension='height', line_color='green',
line_dash='dashed', line_width=2)
p.add_layout(cutoff)
show(p, notebook_handle=True)
def update(new_cutoff_location):
cutoff.location = new_cutoff_location
push_notebook()
interact(update, new_cutoff_location = 1.0)
When I run this code I get ValueError: PATCH-DOC message requires at least one event at push_notebook(). I suspect this indicates that the update to cutoff.location isn't getting detected, so it it looks as if there are no changes to send. Passing the handle doesn't seem to make a difference. Looking at the sample code in this github issue, it looks like there used to be an set method on span elements, but there doesn't appear to be one on my span element cutoff. Maybe there is a different function I am supposed to call to register the change?
I'm on bokeh 0.12.11 with jupyter 1.0.0, jupyter-client 5.1.0, jupyter-console 5.2.0, jupyter-core 4.4.0
This appears to be a regression in Bokeh 0.12.11. Your code works with version 0.12.10 so the immediate workaround is to downgrade. I've made GitHub issue here that you can follow. We will issue a new point release with a fix ASAP.
UPDATE: The issue is now fixed in recent versions of Bokeh

Resources