Cannot use matplotlib library? - matplotlib

I am getting a weird error when calling any function with matplotlib.
import matplotlib as plt
plt.bar(np.arange(7, [1,3,2,1,4,6,1])
I get this error:
IPython.core.display.Javascript object
IPython.core.display.HTML object
Traceback (most recent call last): self.kernel.session.send(self.kernel.iopub_socket, msg_type,*
**AttributeError: 'NoneType' object has no attribute 'session'**
I have already tried:
upgrade my pip
upgrade matplotlib
installing pyplot (which brings error --> Non-zero exit code (1) --> Could not find a version that satisfies the requirement pyplot (from versions: ) No matching distribution found for pyplot)
My Matplotlib version = 3.3.3
OS --> Windows 10
Nothing seems to work and I am stuck. Do you have any idea why this is?

You are importing wrongly the library.
Usually one use
import matplotlib as mpl
(seldom used) or
import matplotlib.pyplot as plt
You are mixing the two imports/names, and so also the interface. Use the second import I wrote, for plt (pyplot).
Ho to debug? When you gain experience, you will learn that usually the problems are in your code and not on environment. So stop upgrading/reinstalling (often you worse the situation, see this site for examples). So try to debug your code. Check the matplotlib page of bar plots. Copy example, modify little things until you have your expected code. (Usually with such steps you find the error).

Related

Can't plot inline in iPython shell (Terminal and VScode terminal window)

can anyone help me to understand, why my iPython shell does not plot inline and in an external window instead? I am not talking about Jupyter notebooks. I made that work. Any help is appreciated and highly welcome. Thank you ...
Of course I tried several sources to tackle my issues.
Stackoverflow: -> didn't work
matplotlib.org -> same
ipython docs -> same
several others suggested by Google -> same
(py310_env) Murat ~ % ipython
Python 3.10.0 (default, Nov 10 2021, 11:24:47) [Clang 12.0.0 ]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.1.1 -- An enhanced Interactive Python. Type '?' for help.
The following code will plot, but **not inline**:
In [1]: import matplotlib.pyplot as plt
In [2]: import numpy
In [3]: %matplotlib
Using matplotlib backend: MacOSX
In [4]: plt.plot([0,1,4,9,16])
Out[4]: [<matplotlib.lines.Line2D at 0x7f7821f3cfa0>]
I also tried this statement:
`%matplotlib inlineĀ“
if I try this one, then I get the following and not even an external display of the plot.
In [6]: plt.plot([0,1,4,9,16])
Out[6]: [<matplotlib.lines.Line2D at 0x7f7823002020>]
<Figure size 432x288 with 1 Axes>
I thought, that maybe my backend needs to be changed so. I tried I couldn`t even change it.
In [8]: %matplotlib qt
Warning: Cannot change to a different GUI toolkit: qt. Using osx instead.
In [9]: matplotlib tk
Warning: Cannot change to a different GUI toolkit: tk. Using osx instead.
Unless someone suggests a better solution, here is my cure.
Initially I had been trying to invoke ipython in the CLI using the command %ipython.
My conclusion is now, you need to use Jupyter Qt-console (available in the Anaconda distro. (Spyder, Jupyter and PyQT are preinstalled)
%jupyter qtconsole : QT will open up Terminal style console for Python and it does the inline plot magic.

Using matplotlib with Qt5 backend with an existing QApplication running, in the same process

We have a Qt5 application that uses PySide2. Recently, we wanted to show plots using matplotlib while our PySide2 application is running in the same process (in a different thread) but then matplotlib crashes (when using PySide2) or freezes before drawing (when using PyQt5).
Here is a minimal sample, uncomment the 23rd line to make matplotlib crash or freeze:
from threading import Thread
from PySide2.QtWidgets import QApplication, QLabel
import matplotlib
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
def start_qt_app():
t = Thread(target=qt_app_thread_func)
t.start()
def qt_app_thread_func():
app = QApplication()
label = QLabel("Hello World")
label.show()
app.exec_()
# Uncomment the line below to make matplotlib crash.
#start_qt_app()
plt.plot([1, 2, 3, 4])
plt.show()
input("Press enter to quit.")
print("Finished.")
My guess is that this is related to the limitation that we can only have 1 QApplication running in a process. So this causes something to go wrong in matplotlib.
How can I solve this problem? One solution that comes to my mind is to create a proxy object for matplotlib that runs matplotlib in another process but I am not sure if this would be the least labor intensive solution. Maybe I can somehow make matplotlib use the existing QApplication? I cannot run our PySide2 app in another process since it uses dynamically created numpy arrays to be passed from main thread to the GUI, and it would cost performance to start it in another process.
As #ImportanceOfBeingErnest points out, matplotlib can live with Qt as the official example shows: Embedding in Qt.
Example:
from PySide2.QtWidgets import QApplication, QLabel
import matplotlib
matplotlib.use('QT5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
if __name__ == '__main__':
app = QApplication()
label = QLabel("Hello World")
label.show()
canvas = FigureCanvas(Figure(figsize=(5, 3)))
ax = canvas.figure.subplots()
ax.plot([1, 2, 3, 4])
canvas.show()
app.exec_()
you should use asyncqt to manage ui and application threads.from asyncqt QEventLoop is a way you can accomplish with
await loop.run_in_executor(exec, method_name)
asyncqt is a spin off library from quamash which is written for PyQt5. example codes are same. So upon your preference, you may use asyncqt with PySide2 or quamash with PyQt5 to make your app responsive when background tasks are running.
asyncqt examples
asyncqt 0.7.0 pypi
Quamash 0.6.1

Google Colab: Why matplotlib has a behaviour different then default after importing pandas_profiling?

When using a notebook in Google Colab, my matplotlib plots have different behaviors whether I import the library pandas-profiling or not.
If I do not import pandas-profiling, the plots are displayed inline by default. But if I import the library, the plots stop being displayed inline.
Workarounds (possible solutions)
Updating the pandas-profiling library before importing it resolves the problem.
Adding %matplotlib inline after importing pandas-profiling resolves the problem.
Reproducing
Run this code in Google Colab to reproduce the problem. Test it with and without importing pandas_profiling. For each test, you will need to terminate the session (Runtime->Manage Sessions->Terminate). Just restarting the runtime is not enough.
import matplotlib.pyplot as plt
# importing the pandas_profiling makes matplotlib
# to stop showing the plot inline
# import pandas_profiling
plt.plot([1, 2], [1, 2])
The expected behavior is to show the plot inline by default, but after importing pandas-profiling, the plots stop being displayed inline.
The real problem
I stumbled upon this problem when my seaborn plotting functions started to break.
For example, consider the following code.
import matplotlib.pyplot as plt
# import pandas_profiling
import seaborn as sns
def plot():
ax = sns.pointplot([1, 2], [1, 2])
print(len(ax.collections))
Now call plot() in two different jupyter cells.
Without pandas-profiling: each function call will print 1.
With pandas-profiling: each function call will add 1 to the previous output.
The problem is in the version of pandas_profiling that is installed by default in Google Colab. The installed version (1.4.1) used to change the matplotlib's backend to agg when imported. The default matplotlib's backend in Colab is module://ipykernel.pylab.backend_inline.
We can see that by running the following before and after importing pandas-profiling:
import matplotlib
matplotlib.get_backend()
This behavior was changed in pull-request #125, which stops changing matplotlib's backend.
Until Google Colab updates the installed version, manually updating it seems to be the best solution. Just run the following in your Colab Notebook:
!pip install --upgrade pandas_profiling

By picture that is displayed in Jupyter notebook isn't shown when running the same code in IDE? [duplicate]

This question already has an answer here:
matplotlib Plot does not appear
(1 answer)
Closed 4 years ago.
I was trying to run code from an online tutorial on my local machine by copying code from Jupiter notebook to my IDE (pycharm).
This part
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
pig_img = Image.open("pig.jpg")
preprocess = transforms.Compose([
transforms.Resize(224),
transforms.ToTensor(),
])
pig_tensor = preprocess(pig_img)[None,:,:,:]
plt.imshow(pig_tensor[0].numpy().transpose(1,2,0))
While Jupiter notebook shows the imagine - I cannot get it displayed when running in terminal or IDE.
Any ideas why?
Thank you
You need to call .show() explicitly to show the image in terminal i.e.
Add this to the end of the code
plt.show()
From the documentation:
Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.

Error getting PySide to work with matplotlib

I am trying to make PySide work with matplotlib, and I have the same problem
described in this thread
Getting PySide to work with matplotlib
trying to launch the PySide + matplotlib example from
http://wiki.scipy.org/Cookbook/Matplotlib/PySide
I have got an error
win.setCentralWidget(canvas)
TypeError: 'PySide.QtGui.QMainWindow.setCentralWidget' called with wrong argument types:
PySide.QtGui.QMainWindow.setCentralWidget(FigureCanvasQTAgg)
Supported signatures:
PySide.QtGui.QMainWindow.setCentralWidget(PySide.QtGui.QWidget)
Adding of
matplotlib.rcParams['backend.qt4']='PySide'
did not help as well as
os.environ["QT_API"] = "pyside"
At the same time PyQt4 examples work.
I use Windows 7, and WinPython 2.7.5.1 (Python 2.7.5, PySide 1.1.2, matplotlib 1.2.1)
Thank you for help!
The problem was in Spyder.
Everything works in other python dev enviroments.
Jed post the solution on another thread just the next day after my question https://stackoverflow.com/a/17376655/2531821