How do I embed Plotly charts exported as HTML in Powerpoint? - python

I am aware of adding URL to PPT, but due to certain privacy issues that cannot be done.
Is there any other way to import plotly charts to ppt? or any equivalent open source app that can be used?
Thank you in advance!

it's pretty straight forward to save as a static image https://plotly.com/python/static-image-export/
create a powerpoint https://python-pptx.readthedocs.io/en/latest/user/quickstart.html#
I don't have powerpoint or a Windows o/s. It's not clear that powerpoint works with active HTML
import plotly.express as px
import pandas as pd
import numpy as np
from pathlib import Path
df = pd.DataFrame({
"time": pd.date_range("1-Jul-2021", periods=200, freq="1H"),
"desired_light": np.random.choice(["ON", "OFF"], 200),
})
# build a figure
fig = px.bar(df, x="time", color="desired_light", height=400, title="Restaurant bills")
# export fingure as a static file: https://plotly.com/python/static-image-export/
fname = Path.cwd().joinpath("SO.png")
fig.write_image(fname)
# create a powerpoint from an image: https://python-pptx.readthedocs.io/en/latest/user/quickstart.html
from pptx import Presentation
from pptx.util import Inches
prs = Presentation()
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
left = top = Inches(1)
pic = slide.shapes.add_picture(str(fname), left, top)
prs.save(Path.cwd().joinpath('SO.pptx'))

Related

Holoviews Bars Ignoring .opts()

I am trying to pass .opts() arguments to style a holoviews .Bars graph, but all arguments are being ignored when passed. This results in the following error:
WARNING:param.Bars02978: Use of call to set options will be deprecated in the next major release (1.14.0). Use the equivalent .opts method instead.
I am on version 1.14.8.
How can I pass the .opts() so my graph can be styled appropriately?
# https://www.youtube.com/watch?v=ZWP_h6WV8h0 Connecting multiple plots
from collections import defaultdict
import panel as pn
import holoviews as hv
from holoviews import opts
import pandas as pd
import numpy as np
import pandas_bokeh
import bokeh
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, TableColumn, DataTable, DateEditor, IntEditor\
, DateFormatter, NumeralTickFormatter, CustomJS, DatePicker, widgets
from bokeh.models import Panel, Tabs, Row
from bokeh.io import show
from bokeh.layouts import Column, layout
import hvplot.pandas
hv.extension('bokeh', 'matplotlib')
renderer = hv.renderer('bokeh')
renderer = renderer.instance(mode='server')
data = {
"calories": [420],
"duration": [50],
"ggg": [60]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)
df2 = pd.DataFrame({'Missing Data': df[['calories']].sum(axis=1), 'Delayed Data': df[['duration']].sum(axis=1)
, 'Duplicate Data': df[['ggg']].sum(axis=1)})
print(df2)
bar_opts = opts.Bars(height=400, width=600, tools=["hover"], bgcolor="grey", xlabel="Wine Class", ylabel="Malic Acid", ylim=(0.0, 3.5))
bars = hv.Bars(pd.melt(df2.reset_index(), ['index']), ['index', 'variable'], 'value', label='dl_refined_analytics').opts(bar_opts)
bars.opts(height=400, width=600, tools=["hover"], bgcolor="grey", xlabel="Wine Class", ylabel="Malic Acid", ylim=(0.0, 3.5))
dmap = hv.DynamicMap(bars)
app = pn.Row(dmap)
app.show() ```
What was the intent behind hv.DynamicMap(bars)? I'm not sure why you'd want to pass the bars object to a DynamicMap constructor, and if you just use app = pn.Row(bars) instead of app = pn.Row(dmap) it should work fine.

How do I add a shadow to AutoShapes using Python-pptx?

I just want to add a shadow to the shapes that I am creating while using python-pptx.
I have read as many documents about using shadows in python-pptx as I can find but I can not figure out how to actually do it.
I tried shadow = shape.shadow to create a 'ShadowFormat' object but when I try to do shadow.visible I get the error AttributeError: 'ShadowFormat' object has no attribute 'visible'
If anyone could explain how this is done and give an example it would be much appreciated!
Extra info:
This is the page linking to the topic: https://python-pptx.readthedocs.io/en/latest/dev/analysis/shp-shadow.html however there is no example on how to create a shadow for a shape in powerpoint.
I have imported the following modules:
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.enum.action import PP_ACTION
from pptx.util import Cm
from pptx.enum.dml import MSO_THEME_COLOR_INDEX
from pptx.enum.text import MSO_AUTO_SIZE
from pptx.util import Pt
I am using python-pptx v0.6.18 and python v3.8
Edit
Example that creates the shape but no shadow appears:
#Import modules
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.util import Cm
from pptx.enum.dml import MSO_THEME_COLOR_INDEX
from pptx.util import Pt
#Open powerpoint file
prs = Presentation('filename.pptx')
#Create a slide
slidelayout = prs.slide_layouts[0]
slide = prs.slides.add_slide(slidelayout)
shapes = slide.shapes
#Add a shape
shape = shapes.add_shape(MSO_SHAPE.ROUNDED_RECTANGLE, Cm(10), Cm(10), Cm(10), Cm(10))
#Create a shadow
shadow = shape.shadow
shadow.inherit = False
shadow.visible = True
shadow.distance = Pt(10)
shadow.shadow_type = 'outer'
shadow.angle = 45
shadow.blur_radius = Pt(5)
shadow.color = MSO_THEME_COLOR_INDEX.ACCENT_5
shadow.transparency = '50'
shadow.distance = Pt(5)
shape.shadow.style = 'outer'
#Save the powerpoint file
prs.save('filename2.pptx')
Example that creates the error message:
#Import modules
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE
from pptx.util import Cm
from pptx.enum.dml import MSO_THEME_COLOR_INDEX
from pptx.util import Pt
#Open powerpoint file
prs = Presentation('filename.pptx')
#Create a slide
slidelayout = prs.slide_layouts[0]
slide = prs.slides.add_slide(slidelayout)
shapes = slide.shapes
#Add a shape
shape = shapes.add_shape(MSO_SHAPE.ROUNDED_RECTANGLE, Cm(10), Cm(10), Cm(10), Cm(10))
#Create a shadow
shadow = shape.shadow
shadow.visible
#Save the powerpoint file
prs.save('filename2.pptx')
The feature <ShadowFormat.visible - applies a reasonable standard shadow override.> is currently out of the scope of pptx.
The command <shadow.inherit = False> is used to remove the default setting with the shadow.
By default, the shadow visibility is set to true. If you want to show the shadow, you can either:
set <shadow.inherit = True>
remove <shadow.inherit = False>
You can use Aspose.Slides for Python to manipulate the shapes. This is a paid library, but you can get a temporary license to evaluate it. The following code example shows you how to add a shape with a shadow to a presentation:
import aspose.slides as slides
# Create a new presentation.
with slides.Presentation() as presentation:
# Create a shape.
shape = presentation.slides[0].shapes.add_auto_shape(slides.ShapeType.ROUND_CORNER_RECTANGLE, 10, 10, 20, 20)
# Set a shadow for the shape.
shape.effect_format.enable_outer_shadow_effect()
shape.effect_format.outer_shadow_effect.distance = 10
shape.effect_format.outer_shadow_effect.direction = 45
shape.effect_format.outer_shadow_effect.blur_radius = 5
shape.effect_format.outer_shadow_effect.shadow_color.color = presentation.master_theme.color_scheme.accent5.color
# Save the presentation.
presentation.save("example.pptx", slides.export.SaveFormat.PPTX)
The result:
Alternatively, you can use Aspose.Slides Cloud SDK for Python. This product provides a REST-based API for presentation processing. It is also a paid product, but you can make 150 free API calls per month for experimentation, learning, and any other purpose. The following code example creates the same shape with the shadow using Aspose.Slides Cloud:
import asposeslidescloud
from asposeslidescloud.apis.slides_api import SlidesApi
from asposeslidescloud.models.shape import Shape
from asposeslidescloud.models.effect_format import EffectFormat
from asposeslidescloud.models.outer_shadow_effect import OuterShadowEffect
slides_api = SlidesApi(None, "my_client_id", "my_client_secret")
# Let's a presentation exists in a storage.
file_name = "example.pptx"
slide_index = 1
color_scheme = slides_api.get_color_scheme(file_name, slide_index)
# Prepare DTO for a shape with the shadow.
shape = Shape()
shape.shape_type = "RoundCornerRectangle"
shape.x = 10
shape.y = 10
shape.width = 20
shape.height = 20
shape.effect_format = EffectFormat()
shape.effect_format.outer_shadow = OuterShadowEffect()
shape.effect_format.outer_shadow.distance = 10
shape.effect_format.outer_shadow.direction = 45
shape.effect_format.outer_shadow.blur_radius = 5
shape.effect_format.outer_shadow.shadow_color = color_scheme.accent5
# Create the shape.
slides_api.create_shape(file_name, slide_index, shape)
I work as a Support Developer at Aspose.

Color tables cells in ppt using python

So I have a excel which contains a table like this:
I want to get the same table in powerpoint using Python
Work Done till now:
Read the excel to python and store in pandas df
Add df to powerpoint
Code for the same effort:
from pd2ppt import df_to_table
import pandas as pd
from pptx import Presentation
from pptx.util import Inches
path =r"Sample PPT.pptx"
prs = Presentation(path)
title_slide_layout = prs.slide_layouts[5]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = "Summary Table"
top = Inches(1.5)
left =Inches(0.25)
width =Inches(9.25)
height= Inches(5.0)
df_to_table(slide, df,left, top, width, height)
All I need is how to do color formatting in this table using Python?
Each cell in a PowerPoint table has its own fill, which can do everything other FillFormat objects can do::
from pptx.dml.color import RGBColor
cell = table.cell(0, 0) # ---or whatever cell you choose---
fill = cell.fill
fill.solid()
fill.fore_color.rgb = RGBColor(0xFA, 0x00, 0x37)
The FillFormat object interface is further described in the documentation here:
https://python-pptx.readthedocs.io/en/latest/api/dml.html#fillformat-objects

ipywidgets graph widget implementation

Good day
I have been on this all day. I am trying to add widgets to my notebooks on my Jupyter(ipython) notebook. Below is my code which makes sense in my head but it is not populating anything. I am trying to control the list of values in StatusesList through a widget so it changes the graph populated. Please help.
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.graph_objs import *
import numpy as np
import cufflinks as cf
init_notebook_mode()
cf.go_offline()
import pandas as pd
cf.set_config_file(theme='pearl')
from __future__ import print_function
from ipywidgets import interact, interactive, fixed
import pandas as pd
import ipywidgets as widgets
from IPython.display import display
df = pd.read_excel("C:\Users\UserName\Downloads\Complaints Management.xlsx")
df_status = df[['Status', 'Member Number']].groupby('Status').count()
StatusesList = df_status.index.tolist()
GragphValueList = df_status["Member Number"].tolist()
# w = Output()
def f(x):
x = StatusesList
return x
interact(f, x = StatusesList)
fig_status = {
'data': [{'labels': x,
'values': GragphValueList,
'type': 'pie'}],
'layout': {'title': 'Complaints by status'}
}
iplot(fig_status)
file sample
I think you are looking for this type of interactivity right?
by_list = ['Priority', 'Status', 'Deadline', 'Query Category'] #df.keys().tolist()
#interact(x = by_list )
def f(x):
df_data = df[[x, 'Member Number']].groupby(x).count()
fig_status = {
'data': [{'labels': df_data.index.tolist(),
'values': df_data["Member Number"].tolist(),
'type': 'pie'}],
'layout': {'title': 'Complaints by %s' % x}
}
iplot(fig_status)
You have control over the by_list by adding or removing string corresponding to fields in your Excel. It is also possible to get all fields using df.keys().tolist() but this might be a little unstable.
PS. Thank you for showing me plotly, I hadn't heard/seen it before but it can produce some nice (interactive) statistical graphs!

How do I work with images in Bokeh (Python)

For example you can plot an image in matplotlib using this code:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('image.png')
plt.imshow(img)
Is something like this possible with Bokeh(0.10)?
You can use the ImageURL glyph (image_url plot method)to load images locally or from the web.
from bokeh.plotting import figure, show, output_file
output_file('image.html')
p = figure(x_range=(0,1), y_range=(0,1))
p.image_url(url=['tree.png'], x=0, y=1, w=0.8, h=0.6)
## could also leave out keywords
# p.image_url(['tree.png'], 0, 1, 0.8, h=0.6)
show(p)
One gotcha - if you graph only an image (and no other data), you'll have to explicitly set the plot ranges.
Here's the docs:
http://docs.bokeh.org/en/latest/docs/reference/models/glyphs.html#bokeh.models.glyphs.ImageURL
The earlier answer was helpful. However, I wanted an image only option without any additional object. So, adding the answer for Bokeh version 0.12.0 and removed all the grids, axes and toolbar.
from bokeh.plotting import figure, curdoc
from bokeh.models import ColumnDataSource, Range1d
bosch_logo = "static/tree.jpg"
logo_src = ColumnDataSource(dict(url = [bosch_logo]))
page_logo = figure(plot_width = 500, plot_height = 500, title="")
page_logo.toolbar.logo = None
page_logo.toolbar_location = None
page_logo.x_range=Range1d(start=0, end=1)
page_logo.y_range=Range1d(start=0, end=1)
page_logo.xaxis.visible = None
page_logo.yaxis.visible = None
page_logo.xgrid.grid_line_color = None
page_logo.ygrid.grid_line_color = None
page_logo.image_url(url='url', x=0.05, y = 0.85, h=0.7, w=0.9, source=logo_src)
page_logo.outline_line_alpha = 0
curdoc().add_root(page_logo)
Another option is to display the image in a div.:
from bokeh.io import output_notebook, show
from bokeh.models.widgets import Div
output_notebook()
div_image = Div(text="""<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/7.png" alt="div_image">""", width=150, height=150)
show(div_image)
ImageURL can't get updated dynamically with a callback. However, using a div, you can do so by treating the div_image.text as a regular Python string, for example:
from ipywidgets import interact
from bokeh.io import output_notebook, show, push_notebook
from bokeh.models.widgets import Div
output_notebook()
div_image = Div(text="""<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png" alt="div_image">""", width=100, height=100)
def update(pokemon_number=1):
div_image.text = """<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{}.png" alt="div_image">""".format(pokemon_number)
push_notebook()
show(div_image, notebook_handle=True)
interact(update, pokemon_number=[1, 4, 7])
Of course, the image source can also point to a local file.
(Tested in Python 3.7.3 and bokeh 1.2.0)
Running this example using bokeh serve is a bit more tricky. I suggest to setup working directory properly:
server_folder/
+main.py
+static/
+logo.png
.. and run bokeh serve command from directory ABOVE server_folder
bokeh serve server_folder --show
Then this code works for me
#main.py file
from bokeh.plotting import figure, curdoc
x_range = (-20,-10) # could be anything - e.g.(0,1)
y_range = (20,30)
p = figure(x_range=x_range, y_range=y_range)
#img_path = 'https://docs.bokeh.org/en/latest/_static/images/logo.png'
img_path = 'server_folder/static/logo.png'
p.image_url(url=[img_path],x=x_range[0],y=y_range[1],w=x_range[1]-x_range[0],h=y_range[1]-y_range[0])
doc = curdoc()
doc.add_root(p)
Here is a simple example that works, almost the same simple format as you requested:
from PIL import Image
import numpy as np
from bokeh.plotting import figure, output_notebook, show
output_notebook()
#load image
im = Image.open('Segment_image.png') # just replace any image that you want here
p = figure()
imarray = np.array(im.convert("RGBA"))
plotted_image = p.image_rgba(image=[imarray.view("uint32").reshape(imarray.shape[:2])], x=0, y=0, dw=imarray.shape[0], dh=imarray.shape[1])
show(p)

Categories