Plotly Python: Export image with different font styles - python

Problem Summary
I'm trying to export a plotly figure with multiple fonts / font stylings as a .png file.
Within the browser, the figure renders correctly. The y-axis has different font style that the rest of the figure.
Both fonts are installed on my system.
But if I try to export the image as a png-file, the different font styling for the y-axis seems to disappear.
Minimum code example
`
import pandas as pd
import plotly.express as px
df = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv")
fig = px.histogram(df, x="Age", color="Sex")
fig.update_layout(font_family="Arial")
fig.update_yaxes(tickfont_family="Arial Black")
fig.show()
fig.write_image("test_image.png")
`
My issue might be related to this post. But both fonts are installed on my machine.
Does anyone know how to include multiple fonts in a plotly figure export?

It seems that the issue has to do with kaleido:0.2.1 when installed via conda.
If kaleido:0.2.1 is installed via pip, the export of images with different font styles works just fine.

Related

No interactivity in plotly plots in Spyder 4

I have recently upgraded to Spyder 4.1.3 (up from Spyder 3.x) and have also consequently upgraded many packages along the way. Plots now show up in the dedicated plots pane (which is a nice addition to Spyder in general). However, now when I generate plots using plotly, there is no interactivity with the resultant plots whether inline or in the plots pane. This used to be there in Spyder 3.x. For example, running the sample code from plotly:
import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df, locations="iso_alpha",
color="continent", # which column to use to set the color of markers
hover_name="country", # column added to hover information
size="pop", # size of markers
projection="natural earth")
fig.show()
The plot shows up in the plot pane but when I hover over it with the mouse nothing pops up. When I run the same code in Jupyter I do get the interactivity. Any ideas about how to get this functionality going in Spyder 4?

How to save a Plotly graph in a ipynb file?

I understand that it is possible to export a Plotly graph, and that I can display it.
While sharing notebooks, the matplotlib plots remain intact in the Jupyter Notebooks, however, the Plotly graphs do not. They simply disappear
I understand that the Plotly graph is browser rendered, but is there any way I can store the graph in the ipynb file when I export it?
Is there any way that I can display the Plotly graph, just like the matplotlib graph?
Edit: As suggested in an answer, I tried to save it to a figure object, and display that, but no luck there either :/
If you put the code for a series of graphs in a single cell, execute it and save it, I think it will be displayed the next time you open it.
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.show()

Alternatives of saving an interactive figure in plotly other than Interactive HTML Export

I stumbled upon a need where I need to save an interactive figure which is plotted in Python by using plotly.
After hours of googling and whatnot, I found 2 solutions given in the plotly documentation to save a figure:
1. Static Image Export
2. Interactive HTML Export in Python
Interactive HTML Export fulfilled my need but left me wondering can't I use other interactive image formats i.e gif etc.
Please use the below code to find ways of saving this figure other than .html.
df = px.data.gapminder()
fig = px.scatter_geo(df, locations="iso_alpha", color="continent",
hover_name="country", size="pop",
animation_frame="year",
projection="natural earth")
fig.show() # Used for showing output in jupyter notebook
fig.write_html('output.html') # actually used for exporting as an .html file
Thank you in advance.

How to use Python Seaborn Visualizations in PowerPoint?

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.

Pycharm jupyter cell background

I'm using PyCharm with Darcula theme and Jupyter notebook from anaconda package.
I faced a problem that Darcula theme is inconvinient to use with Jupyter notebook
For example, pandas plot's axis is not readable.
I tried to find out, how to change notebook cell background, but looks like that there is no possibility to do that.
Of course, I can change PyCharm theme to another, but I used to work under this theme.
And of course, I can change background of plot in code, but it is inconvinient to change background for each plots (for example, if I work with ready notebook)
Can I change cells background or the only way is to change theme to another?
Probably a bit too late, but here is a solution for future reference:
1 - Go to PyCharm > Preferences and type in the search bar "Invert image outputs for dark themes"
2 - Go to Language & Frameworks > Jupyter and uncheck the "Invert image outputs for dark themes" box.
3 - Restart PyCharm for option to take effect.
Per https://stackoverflow.com/a/40371037/2529760, you can use
fig = plt.figure()
fig.patch.set_facecolor('white')
or
plt.gca().patch.set_facecolor('white')
to force a white background beneath the axis labels on a per-plot basis. You can use
plt.rcParams['figure.facecolor'] = 'white'
to achieve this on a per-notebook basis.
To change this setting globally, normally you can edit the matplotlibrc file, but it appears Jupyter overrides this to some degree. Following https://nbviewer.jupyter.org/github/mgeier/python-audio/blob/master/plotting/matplotlib-inline-defaults.ipynb, you can create a file ipython_kernel_config.py at the correct location (~/.ipython/profile_default by default) containing the line
c.InlineBackend.rc = {'figure.facecolor': 'white'}
Any of these options will ensure the plot has a white background so the text is legible.
You can try the seaborn package:
import seaborn as sns
sns.set_context('notebook')
sns.set_style('white')
It will change the output plot background to white.
The temporary workaround for me is to explicitly call plt.show() at the end of cell.
I am also looking for a better solution.

Categories