I created some figures with Seaborn in a Jupyter Notebook. I would now like to present those figures in a PowerPoint presentation.
I know that it is possible to export the figures as png and include them in the presentation. But then they would be static, and if something changes in the dataframe, the picture would be the same. Is there an option to have a dynamic figure in PowerPoint? Something like a small Jupyter Notebook you could Display in the slides?
You could try Anaconda Fusion (also the video here), which let's you use Python inside of Excel. This could possibly work since you can link figures/data elements between Excel and PowerPoint (but special restrictions might apply when the figure is created via Python rather than standard Excel). Anaconda Fusion is free to try for a couple of months.
Another solution would be to use the Jupyter Notebook to create your presentation instead of PowerPoint. Go to View -> Cell Toolbar -> Slideshowand you can choose which code cells should become slides.
A third approach would be to create an animation of the figure as the data frame changes and then include the animation (GIF or video) in PowerPoint.
The following procedures probably won't be the most elegant solution, but it will let you produce a Seaborn plot, store it as an image file, and export the same image to an open powerpoint presentation. Depending on whether you set LinkToFile to True or False, the images will or will not update when the source changes. I'm messing around with this using cells in Spyder, but it should work in a Jupyter notebook as well. Make sure that you have a folder named c:\pptSeaborn\.
Here it is:
# Some imports
import numpy as np
import seaborn as sns
import os
import matplotlib.pyplot as plt
import win32com.client
import win32api
os.chdir('C:/pptSeaborn')
# Settings for some random data
mu = 0
sigma = 1
simulation = np.random.normal(mu, sigma, 10)
# Make seaborn plot from simulated data. Save as image file.
def SeabornPlot(data, filename = 'c:\\pptSeaborn\\snsPlot.png'):
ax = sns.kdeplot(data, shade=True)
fig = ax.get_figure()
fig.savefig(filename, bbox_inches='tight', dpi = 440)
plt.close(fig)
# Import image file to active powerpoint presentation
def SeabornPPT(plotSource, linkImage):
Application = win32com.client.Dispatch("PowerPoint.Application")
Presentation = Application.Activepresentation
slidenr = Presentation.Slides.Count + 1
Base = Presentation.Slides.Add(slidenr, 12)
gph = Base.Shapes.AddPicture(FileName=plotSource,
LinkToFile=linkImage, SaveWithDocument=True,
Left=50, Top=25, Width=800, Height=500)
Presentation.slides(slidenr).select()
# Produce data, save plot as image, and export image to powerpoint
SeabornPlot(data = simulation)
SeabornPPT(plotSource = 'c:\\pptSeaborn\\snsPlot.png', linkImage = False)
Now, if you have an open powerpoint presentation and run this whole thing five times, you will get somthing like this:
If you go ahead and save this somewhere, and reopen it, it will still look the same.
Now you can set linkImage = True, and run the whole thing five times again. Depending on the random data generated, you will still get five slides with different graphs.
But NOW, if you save the presentation and reopen it, all plots will look the same because they're linked to the same image file:
The next step could be to wrap the whole thing into a function that takes filename and LinkToFile as arguments. You could also include whether or not the procedure makes a new slide each time an image is exported. I hope you find my sggestion useful. I liked your question, and I'm hoping to see a few other suggestions as well.
We now went with this approach:
You can save the figures as a .png file and insert this into Powerpoint. There is an Option when inserting it, that the Picture will be updated every time you open PowerPoint, retrivining a new version of the file from the Folder I saved it to. So when I make changes in Seaborn, a new version of the file is automatically saved as a Picture which will then be updated in PowerPoint.
Related
I'm trying to save plots, generated with holoviews using the bokeh backend, to a png. To do this I'm using the following code
import holoviews as hv
from holoviews.operation.datashader import datashade
curve: hv.Curve = hv.Curve(__some_data_for_curve__)
hv.save(datashade(curve), output_path, backend=bokeh)
Unfortunately the saved png is not rendered properly:
When I instead use
import panel as pn
import holoviews as hv
from holoviews.operation.datashader import datashade
curve: hv.Curve = hv.Curve(__some_data_for_curve__)
pn.serve(datashade(curve))
I get a nicely rendered Plot:
This leads to the assumption that datashader does not properly render the image when just saving the plot to file. Does anybody have an idea on how to get datashader to finish rendering before saving?
Good question about a subtle issue.
What's happening is that hv.save exports the "initial" rendering of a HoloViews object, before any subsequent hooks or streams take effect. The initial rendering includes an RGB image that is the result of HoloViews calling Datashader with initial height and width values determined by arguments to the datashade call (height=400 and width=400 by default). When you are viewing the plot interactively, the initial call is soon updated and overwritten with the size of the actual frame used in the plot as it gets laid out on your screen. Because your screen is usually much larger than 400x400, you won't normally even see the low-res version unless you save the file.
The other issue is that the default height and width are deliberately set to relatively low values, in order not to waste much time on a plot that most users will never see.
If you want the initial save to use a higher resolution, you can add arguments to the datashade call with specific values like height=400, width=1024 or you can just tell it "scale up by 4X" using pixel_ratio=4.
You can also set those parameters globally at the start of your script or notebook, if you always want high-res exports:
from holoviews.operation.datashader import ResamplingOperation
ResamplingOperation.width=1000
ResamplingOperation.height=1000
ResamplingOperation.pixel_ratio=2
Or if you always want higher res, you can put those settings into your ~/.config/holoviews/holoviews.rc file.
Apologies if this has been asked somewhere before, but I couldn't find a good answer. I'm trying to take an image URL obtained from scraping a website and use it to paste the image into an Excel worksheet without saving the image somewhere first. I guess this would be equivalent to right-clicking the image, copying, then pasting into Excel if someone were to try this manually.
Right now, I'm using skimage to get the image to pop up:
from skimage import io
io.imshow(io.imread('urlhere.com'))
io.show()
However, I don't think there is a way to work with the image like this and paste it into Excel using xlwings. I've seen people mention things like urllib.request.urlretrieve and PIL but these only seem to work if I want to save the image somewhere first and then bring it into Excel.
I feel like I'm missing some kind of obvious answer, but is there a way to skip the saving part and just copy the image from its URL to put it somewhere else?
Thanks!
After much trial and error, I was able to figure this out so I thought I'd post the answer:
xlwings only allows for pictures from a filepath or matplotlib figures to be added to Excel files. Therefore, I had to create a matplotlib figure of the image, turn its axes off, and insert it into the Excel file. There may be a better way to do it, but this is what worked for me:
from matplotlib import pyplot as plt
from skimage import io
import xlwings as xw
image_url = 'urlname.com'
fig = plt.figure()
plt.axis('off')
plt.imshow(io.imread(image_url))
wb = xw.Book(r'file\path\document.xlsm')
dashboard = wb.sheets['sheet1']
dashboard.pictures.add(fig)
Is there way to save a "Figure" in matplotlib to a file such that if you later wanted to modify the Figure, e.g. change data points, resize the figure, etc. you could load up the file in a new python script and do that?
Right now I save the majority of my plots as Pdfs, but that doesn't allow me to make edits later on. I have to go dig up my old source code and data files. I've lost track of the number of times I've lost the plot-generating code and have to essentially reproduce it all from scratch.
It would be nice if I could just save a plot as a self-contained data file, like Photoshop does with its .psd files, so that I can just load it up directly, type "object.plot()", and not have to worry about external dependencies. Does such a format exist, or if not is there any way I could achieve this?
There is a method of saving the plotted object called pickling. I don't have much experience with it but it should allow you to save the plot to a file using
fig = plt.figure
pl.dump(fig, file('file_name.pickle','w'))
and using
fig = pl.load(open('file_name.pickle','rb'))
fig.show()
to load the saved graph.
Matplotlib warns that, "Pickle files are not designed for long term storage, are unsupported when restoring a pickle saved in another matplotlib version". To be safe, I would just save the array containing the data to the plot to either a .csv or .txt file, and keep this file in a folder with the python file to plot the graph. This way you will always be able to plot your data (no matter the version of matplotlib you are using). You will also have the data and code in the same place, and you can easily read the data from the .csv or .txt file, save it to arrays, and graph it using
file = open("file_name.txt", "r")
if file.mode == 'r':
data = f.read().splitlines()
data_array1 = data[0].split(",")
data_array2 = data[1].split(",")
p, = plt.plot(data_array1, data_array2)
I also suggest uploading your python files along with your .csv or .txt files to Github.
If you would like to read more about pickling in matplotlib I suggest reading the two pages linked below.
(1) Pickle figures from matplotlib
and (2) https://matplotlib.org/3.1.3/users/prev_whats_new/whats_new_1.2.html#figures-are-picklable
i'm a beginner in python, i really don't know how create an animation. I have different plots and i want to create a short video that concatenate these plots.
import pandas as pd
import matplotlib.pyplot as plt
data=[[1,1,3],[1,2,1],[2,1,9],[2,2,0]]
a=pd.DataFrame(data)
a.columns=['x','y','value']
data2=[[1,1,5],[1,2,2],[2,1,1],[2,2,3]]
b=pd.DataFrame(data2)
b.columns=['x','y','value']
data3=[[1,1,15],[1,2,7],[2,1,4],[2,2,8]]
c=pd.DataFrame(data3)
c.columns=['x','y','value']
final=[a,b,c]
for i in range(0,len(final)):
fig, ax = plt.subplots()
plt.scatter(final[i]['x'],final[i]['y'],c=final[i]['value'],vmin=0, vmax=15,)
plt.colorbar()
Python isn't really the way to go for creating a video.
If you want to present your graph(s) in video format, screenshot them using Windows Button + Print Screen (PrtSc) on your keyboard. This will save a screenshot to your pictures folder. Then, use a video editor, such as Vegas or free options like WeVideo to put the screenshots into a video.
You can also use presentation software, like Prezi, for a more engaging experience.
I've got a Python script (3.5) that will go through a whole battery of tests. The user gets to select which tests get run out of N possible tests. So, the user could run 1 tests up to N tests.
Right now, I'm just outputting the results of the test to a plot with matplotlib and that looks OK, but they're just saved as individual files. Also, the code has some PASS/FAIL criteria for each test.
So, the issue is, I would like to use some tool with Python to output the whole story of the test sequence as a PDF. I'd like to be able to keep some Boiler-Plate stuff and update some stuff in the middle....For example:
Test was run for 7 minutes. Maximum power was recorded as -69.5dBm.
The thing that is the same each time is:
Test was run for minutes. Maximum power was recorded as dBm.
And, the number of minutes and the number for maximum power is pulled in from the results of the test. Also, the graph is pulled in from 'matplotlib'.
So, for each test, I'd like to append some Boiler-plate text, fill in some blanks with real data, and slap in an image where appropriate, and I'd like to do it with Python.
I looked at some of the suggestions on SO, but for the most part it looks like the solutions are for appending or watermarking existing PDFs. Also, Google turns up a lot of results for automating the generation of Python Code Documentation...Not Code for generating Documentation with Python.
Reportlab looked promising, but it looks like it's been abandoned.
Also, I'm not married to the requirement that the output be a PDF. This is for internal use only, so there's some flexability. HTML, Word or something else that can be converted to a PDF manually by the user afterwards is fine too. I know PDFs can be somewhat troublesome due to their binary nature.
You can do all of this directly in matplotlib.
It is possible to create several figures and afterwards save them all to the same pdf document using matplotlib.backends.backend_pdf.PdfPages.
The text can be set using the text() command.
Here is a basic example on how that would work.
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
N=10
text = "The maximum is {}, the minimum is {}"
# create N figures
for i in range(N):
data = np.random.rand(28)
fig = plt.figure(i+1)
ax= fig.add_subplot(111)
ax.plot(np.arange(28), data)
# add some text to the figure
ax.text(0.1, 1.05,text.format(data.max(),data.min()), transform=ax.transAxes)
# Saving all figures to the same pdf
pp = PdfPages('multipage.pdf')
for i in range(N):
fig = plt.figure(i+1)
fig.savefig(pp, format='pdf')
pp.close()