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

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.

Related

Cannot use matplotlib library?

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).

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

ipython pylab figures not inline

I've installed iPython + SciPy Superpack on a Mac (OSX Lion).
If I plot using matplotlib.pyplot, it will pop up a window with the graph, and I close this for the ipython kernel to continue.
from matplotlib import pyplot as plt
plt.plot([1, 2, 3], [3, 6, 9])
plt.show()
However, If I try the inline (starting with --pylab inline or --pylab=inline) and import pylab, instead of a plot inside the notebook (which I expect), I get an external window, which never renders anything.
Still in an external window:
import pylab
pylab.plot([1, 2, 3], [3, 6, 9])
pylab.show()
Since I've started the notebook with ipython notebook --pylab=inline it should already be so, but if I use %pylab inline in a cell and run it, I get the help, and the same code above creates a blank window, and hangs the kernel - I can only force kill the window.
How should this work?
Okay - the problem was that the original ipython notebook process was still running (I'd not killed it) and the new one with the inline flag was running on a different port.
If you are having this issue - first save all your notebooks, then check you haven't got other processes running and kill any that shouldn't be running.
If you want to avoid this confusion, you can set NotebookApp.port_retries=0 in your configuration, in which case later notebook calls will give up, rather than listen on a new port. (Credit to minrk, in comments)