Search code examples
pythonplotlypowerpoint

convert plotly figure to image and then use this image as normal PNG


I'm trying to convert a plotly express figure to image, then use this image to save it on a power point slide. This is my code:

import plotly.express as px
import plotly.io as pio
from pptx import Presentation


wide_df = px.data.medals_wide()

fig = px.bar(wide_df, x="nation", y=["gold", "silver", "bronze"], title="Wide-Form Input, relabelled",
             labels={"value": "count", "variable": "medal"})

# Convert the figure to a bytes object
img_bytes = pio.to_image(fig, format='png')

ppt = Presentation(
     "template.pptx"
 )

slide = ppt.slides[3]
placeholder = slide.placeholders[13]

placeholder.insert_picture(
           img_bytes
       )

But I'm getting the following error message:

'bytes' object has no attribute 'seek'

Solution

  • You should be able to do:

    import io
    
    ...
    ...
    placeholder.insert_picture(io.BytesIO(img_bytes))
    

    The clue was the error message that there is no seek attribute, which is a method that "file-like" objects have in Python, and io.BytesIO() is a way of making a bunch of data appear to come from, and behave like, a file. Documentation is here.