anybody know how to save image output from cells in jupyter notebook? - python

unlike google colab i cant right click to save the image, i use vscode on a chromebook with linux beta, it would be helpful if you provide step-by-step instruction. I am also new to code and the notebook uses python
p.s this is for dall.e flow-jupyter

On the right we have two options, first one is to expand image (or zoom) and second option is to save image.
But best option is to use code to save image instead of saving images manually.
For example, if you want save pandas graph, then
import pandas as pd
import matplotlib.pyplot as plt # pandas uses matplotlib in the backend
df = pd.DataFrame({"a": list(range(50))})
df["a"].plot()
plt.savefig("test.png")

Related

Python Plotly SVG Graphics Weird Font Issue

I am trying to create a sunburst plot using Plotly. Everything is working fine except that after exporting that newly created SVG file into Overleaf and then creating PDF using LaTeX code, the image looks so weird. The texts are getting out of the image and overlapping with each other. Check the demo image here.
Here is the code I used to produce the image.
import pandas as pd
import plotly.express as px
import os
df = pd.read_excel('data/countries.xlsx')
df.head()
fig = px.sunburst(df, path=['Continent', 'Country'])
fig.show()
graphics_dir = "graphics"
if not os.path.exists(graphics_dir):
os.mkdir(graphics_dir)
fig.write_image(format='svg', file='{}/countries.svg'.format(graphics_dir))
I know how to fix this problem when I am generating graphics using Matplotlib from this link and it is working for me. But I do not know how to achieve this in Plotly.
I have managed to hack the whole process with advice from one of my colleagues. As I could not disable the font path from SVG, I have chosen another method.
First, I converted the SVG file into PDF, and then I used the PDF instead of that SVG file. The benefit of converting SVG to PDF is that the font path of the SVG is no more available in the PDF. They become embedded into the PDF.
This way, I have managed to fix the issue! Thanks.

Jupyter and %matplotlib inline lost axis

I am having a really weird issue with using the %matplotlib inline code in my jupyter notebook for plotting graphs using both pyplot and the pandas plotting function.
The problem is they show up without any axes, and basically just show the graph area without anything aside from data points.
I found adding:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
reverse it, but I find it odd that should do that every time as the effect disappears as soon as I run %matplotlib inlinecommand.
an example could be
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(A,A)
plt.tight_layout()
plt.xlabel('here')
plt.show()
This would generate the graph below:
Weird enough if I uses the savefig it get plotted with the axis, if I uses the right-click -> new output -> save as figure, I also get the graph with the figures !!
like this:
Can anyone help me understand what is wrong, which global setting did I mess up, and how do I revert it?
(I don't remember messing around with any settings aside from some settings for pandas, but don't think they should have had an impact)
as mentioned running mpl.rcParams.update(mpl.rcParamsDefault) command does bring it back to normal until I run %matplotlib inline` again !!
Any help would be much appreciated.
Okay I am sorry I think I can answer the question myself now.
With the helpfull #Mr. T asking for the imgur link made me realize what was going on. I had starting using the dark jupyter lab theme, and the graph would generate plots with transparent background, ie. the text and lines where there, but I just couldn't see them.
The trick is to change the background color preferably globally, but that will be a task for tomorrow.

Showing numpy array as image with animation

I have a 2D numpy array which I want to show as an image. Now using matplotlib plt.imshow(my_array) works fine. The problem is that my array keeps on changing. There is a function foo() which changes the array. I want to show that array as image and also the changes done by foo function. It should be only one image window and the updates are done in that window instead of creating new one. FuncAnimation is one way but it is used with plots. How can I use it to show image?
My image is actually an arena of obstacles. I am trying to show path finding and visualise it. Breadth-First Search and Dijkstra's algorithm I am trying to visualise.
Kindly help. Thank you.
Not knowing how your code is structured but one solution to your problem could be using plt.pause()
An example,
import numpy as np
from matplotlib import pyplot as plt
def draw_me(img):
plt.pause(.01)
plt.imshow(img)
for idx in range(12):
img = np.random.randint(0, 255, (12,12))
draw_me(img)
note if you are using Sypder make sure you're not inline ploting in the console. For me that means entering the following in the console,
%matplotlib auto
%matplotlib qt

Matplotlib plt.show() doesn't display anything

I want to create a barchart for my dataframe but it doesn't show up, so I made this small script to try out some things and this does display the barchart the way i want. The dataframe is structured the exact same way (I assume) as my big script where all my data is transformed.
Even if I copy paste this code in my other script it doesn't show the the plot
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
'soortfout':['totaalnoodstoppen','aantaltrapopen','aantaltrapdicht','aantalrectdicht','aantalphotocellopen','aantalphotocelldicht','aantalsafetyedgeopen', 'aantalsafetyedgeclose'],
'aantalfouten':[19,9,0,0,10,0,0,0],
})
print(df)
df.plot(kind='bar',x='soortfout',y='aantalfouten')
plt.show()
I can't really paste my other code in here since it's pretty big. But is it possible that other code that doesn't even use anything from matplotlib interferes with plotting a chart?
I've tried most other solutions like:
matplotlib.rcParams['backend'] = "Qt4Agg"
Currently using Pycharm 2.5
It does work when i use Jupyter notebook.
I was importing modules that i wasn't using so they were grayed out.
But apparently you shouldn't use import pandas_profiling if you want to plot with matplotlib
Don't import modules that can interfere with plotting like pandas_profiling

Precompute Jupyter widget results and embed in HTML

I'm currently working on a Jupyter notebook that creates an energy level diagram using matplotlib. One parameter of the underlaying spectrum computation can be varied using an interact statement. Now I want to export this notebook to HTML while the widget functionality should stay intact. Is it possible to precompute all possible outcomes and include them into the HTML version? Users should be able to use the interact feature without having to connect to a kernel.
Thanks for advice.
Peter
EDIT: I hope to clarify my question with the following sample code:
from ipywidgets import interact
import matplotlib.pyplot as plt
import numpy as np
def f(a):
x = np.linspace(0,2,100)
plt.plot(x,a*x**2)
plt.ylim([0,20])
plt.show()
return None
interact(f, a=(1,5,1))
In the final HTML file all possible images (in this case all parabolas with a=1...5) should be included (in this sense pre-computed) and then displayed when the user selects the appropiate value with the slider.

Categories

Resources