How to make figure legends and ticks visible in JupyterLab dark theme? - matplotlib

When using JupyterLab (Version 0.32.0) dark theme, figure ticks and legends are invisible because the foreground and background colors are very close. How to make them visible?
Following are some screenshots for illustration:
Plotting code:
import matplotlib.pyplot as plt
%matplotlib inline
plt.subplot()
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
plt.legend(bbox_to_anchor=(1.05, 1), loc=2,
frameon=False)
Output figure in the light theme:
The same output figure in the dark theme:
Notes:
This question has been asked multiple times in Github Issues of both JupyterLab and Matplotlib, and it has been answered by telamonian and blink1073. I repost and re-answer the question here for easier lookup for the answer.
According to issue 3855 of JupyterLab, upcoming versions may fix this issue.

Just to quote telamonian and blink1073's manual workaround here:
plt.style.use('dark_background')
Following is a short demo:
Code:
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('dark_background')
plt.plot(list(range(10)), list(range(10)))

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.

matplotlib grid setting (python)

I made some changes of matplotlib settings and can't figure out how to put it back. it would be great if you can help me out!
original settings
image that i see now
You question lacks relevant information such as exactly what did you change. In any case something like this should solve your problem:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
Try this:
import matplotlib.pyplot as plt
print plt.style.available
which will give you the list of available styles on your machine ('classic','seaborn', etc).
From here you can set which existing plot style you want to use with
plt.style.use('classic')