I tried to render several hundred images with python and matplotlib using the following code:
def render_state(np_data_array):
filename = "render/fig_" + str(i) + ".png"
fig = plt.figure(figsize = (12,12) )
aa = fig.add_subplot(111)
aa.imshow(np_data_array,cmap='gray')
fig.savefig(filename)
unfortunately matplotlib is also rendering everything into the jupyter notebook.
Is there a way to prevent any output from matplotlib? I couldn't really find a way and most answers on the internet just say to not use plt.show() what I don't even use
%%capture as the first line of the cell works like charm!
Thanks to ImportanceOfBeingErnest
You can also just use plt.close() at the end of your notebook cell like explained here. This way, you can still render other widgets like a tqdm progress bar. With %%capture, all widgets are blocked.
Related
I tried the following example 3D Mesh example with AlphaNull to test alphahull but my jupyter notebook display just something blank.
When I set alphahull=5, the display is blank:
But when i set alphahull = 0, it works:
and when i set alphahull = -1, it works :
Why is this happening and how can I fix it?
Thank you in advance for your help.
Unfortunately I think rendering for alphahull values larger than 0 may be broken as of the latest plotly update. I noticed that in the documentation page, their code example with alphahull=5 also doesn't render. I tried with other positive values and none of these render either (the same alpha shape algorithm is used for any alphanull > 0)
However, I tried downgrading to plotly==4.14.0 and the same example with alphahull=5 does render.
import plotly.graph_objects as go
import numpy as np
pts = np.loadtxt(np.DataSource().open('https://raw.githubusercontent.com/plotly/datasets/master/mesh_dataset.txt'))
x, y, z = pts.T
fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z,
alphahull=5,
opacity=0.4,
color='cyan')])
fig.show()
So in your jupyter notebook, you can run the line !pip install plotly==4.14.0 in a separate cell and see if that allows you to render positive alphahull values.
I use latex in matplotlib by setting
plt.rcParams.update({'mathtext.fontset': 'stix'})
plt.rcParams.update({'font.family': 'STIXGeneral'})
I am using the letter $\ell$ very often in my research and there is a small detail bothering me. As you can see below, matplotlib renders the symbol with the little loop smaller and the letter more slanted. To me it almost looks like a vertically stretched $e$. I tried using the "\mathrm{\ell}" command instead but it did not change anything.
Is there any way I could get the symbol to look normal?
PS: it looks like stackoverflow is not detecting the math mode $ for some reason. If you know how to fix it (or if I am doing something wrong) please point it out or edit the question. Thanks!
The reason is the font you are using in matplotlib. With the following settings, for example, you get the same letter as in overleaf:
import matplotlib.pyplot as plt
import numpy as np
# Example data
t = np.arange(0.0, 10, 1)
s = np.arange(0.0, 10, 1)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.xlabel(r'$\ell$', fontsize=30)
plt.ylabel(r'$\ell$', fontsize=30)
plt.plot(t, s)
plt.show()
You get:
However, In Jupyterlab I could not reproduce. It used the overleaf fonts even with your settings.
This proved to be the simplest solution for me. Thanks the others for pointing out the font being the issue.
Rather than
plt.rcParams.update({'mathtext.fontset': 'stix'})
plt.rcParams.update({'font.family': 'STIXGeneral'})
I now write the first line as
plt.rcParams.update({'mathtext.fontset': 'cm'})
which works like charm. This is helpful if you are someone like me not using TeX but just the mathtext matplotlib built-in function.
I'm new to python and programing and I'm trying to make a code to display an image with some data from a .fits file. I'm first trying to make this example I found from this site: https://docs.astropy.org/en/stable/generated/examples/io/plot_fits-image.html#sphx-glr-download-generated-examples-io-plot-fits-image-py. When I run it, it shows everything it should, except the figure, which is the most important part. How do I make the figure show up?
The code is the following:
import matplotlib.pyplot as plt
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
from astropy.utils.data import get_pkg_data_filename
from astropy.io import fits
image_file = get_pkg_data_filename('tutorials/FITS-images/HorseHead.fits')
fits.info(image_file)
image_data = fits.getdata(image_file, ext=0)
print(image_data.shape)
plt.figure()
plt.imshow(image_data, cmap='gray')
plt.colorbar()
Appending plt.show() at the end of your code should work ...
I ignored the fact that the figure was not showing up in the example and went straight to my .fits file. With that file the figure worked fine. Turns out there was probably something wrong with the example file.
This answer from a few years ago shows how you can make jupyter notebook create graphs as svg. The solution is to tell the InlineBackend to use svg as output.
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
plt.plot(...)
This will cause all images to be in svg format inside the notebook as well as in the produced ipynb file; the file will have a line like
"data": { "image/svg+xml": [ "<?xml .....
in it.
The problem is now that this does not work if the %matplotlib notebook backend is used. %config InlineBackend does not change anything for the notebook backend, hence the output file contains a PNG image
"data": { "text/html": [ "<img src=\"data:image/png;base64,iVBORw0....
So the question is: How do I get the ipynb file to include a static version of the plot that is created with the %matplotlib notebook backend as SVG image?
There is a small comment by #mark jay from one month ago, who wanted to do exactly what I would like to do now, but there is no answer or hint to that comment.
In my code I have plotted directly from the dataframe:
%matplotlib notebook
import pandas as pd
df = pd.read_sql(sql1, connection)
...
...
df.plot(subplots=True, kind='bar')
This functions perfectly well without importing matplotlib.pyplot but it also can't be coerced to create the graphic as an svg. I suppose if the base case would work, I could modify the plotting code so it did not involve pandas or dataframes.
Since apparently even after a bounty period noone was able to provide a solution, a workaround may be the following.
Create you notebook with %matplotlib notebook. Once you're satisfied with the result, save it.
Use a copy of it and replace %matplotlib notebook with
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
Rerun the complete notebook. Save the result.
Open the resulting ipynb file in a text editor and replace the previous two lines again with %matplotlib notebook.
The final result will be a ipynb with svg images. But once opened and run, it will use the notebook backend for figure creation.
From whatI understand from reading about matplotlib backends, nbagg, which is called using %matplotlib notebook uses the Agg (Anti-Grain Geometry) render which is not capable of rendering vector graphics. Unfortunately this is the only out of the box way of using an interactive inline backend for Jupyter.
Docs Link https://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode
Similar Answer How to make matplotlibs nbagg backend generate SVGs?
If you don't need the interactivity just keep use
import pandas as pd
from IPython.display import SVG, display
from numpy import ndarray
def svg_add(chart, size=(4,4), dpi=100):
"""Takes a chart, optional tuple of ints for size, int for dpi
default is 4 by 4 inches with 100 dpi"""
if type(chart) == ndarray:
fig = chart[0].get_figure()
fig.set_size_inches(size)
fig.savefig("mybar.svg", dpi=dpi)
display(SVG(filename='mybar.svg'))
else:
fig = chart.get_figure()
fig.set_size_inches(size)
fig.savefig("mybar.svg", dpi=dpi)
display(SVG(filename='mybar.svg'))
then
df = pd.DataFrame([[2,5]],columns=['a','b'])
bar_chart = df.plot(subplots=False, kind='bar')
svg_add(chart=bar_chart,size=(3,3),dpi=100)
#or
#svg_add(bar_chart,(3,3),100)
I'm using python 2.7 on Ubuntu to draw charts from text files containing data.
My point is, when using python executables in shell, I have no problem recording plots, but if I want them shown on my screen instead I have to go through the graphic interface. If possible, I would very much like to skip that part and get a dynamic display that I can interact with (as if I were to run my script from a python shell)!!
a MWE of what i'm doing is :
MWE
import numpy as np
import matplotlib.pyplot as plt
with open('filename','r') as myfile:
DATA = np.genfromtxt(myfile,unpack=True)
fig = plt.figure()
... my plot configuration ...
plt.savefig("image_name"+'.png')
plt.close()
end of MWE
Using this script image_name.png appears in my repertory. I tried replacing the last 2 lines with plt.plot() and plt.draw() but nothing happened.
Many thanks!
Michel
(edited)