python xlsxwriter 将数据框和绘图导出到一个 Excel 中的不同选项卡

Mat*_*her 1 python export graph xlsxwriter

我正在尝试将一些数据框和绘图导出到一个 Excel 中的不同选项卡。每个选项卡应仅包含一个数据框或图表。我已经完成了数据框导出部分,但我不知道如何使用类似的逻辑导出绘图。

Xlsxwriter:导出两个数据帧:表和misc_user

writer = pd.ExcelWriter(path_output + '\Report_{}.xlsx'.format(*arg), engine='xlsxwriter')

table.to_excel(writer, sheet_name='Uploads')
misc_user.to_excel(writer, sheet_name='Misc Users')

writer.save()
Run Code Online (Sandbox Code Playgroud)

然后我有两个由另外两个数据框制成的绘图

# plotly 
user_evt_long = px.line(user_evt_long, x='Month', y='Times', color='ELEVATE?')

# Show plot 
user_evt_long.show()
Run Code Online (Sandbox Code Playgroud)
top_users_fig = px.bar(top_users, x='account_name', y='users_count', title = 'Top Ten Uploads')

top_users_fig.show()
Run Code Online (Sandbox Code Playgroud)

所以总共应该有四个选项卡。“上传”选项卡包含table、“其他用户”选项卡包含misc_user、“用户”选项卡包含user_evt_long、“热门用户”选项卡包含top_users_fig

如何导出user_evt_longtop_users_fig使用与数据框导出类似的逻辑?

jmc*_*ara 5

以下是将 Plotly 图像添加到与 Pandas 数据框相同的工作表以及新工作表中的示例。

import plotly.express as px
import pandas as pd
from io import BytesIO


# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_plotly.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Make a plotly chart.
fig = px.bar(df)

# Convert it to a BytesIO stream.
image_data = BytesIO(fig.to_image(format="png"))

# Write the image to the same sheet as the data.
worksheet.insert_image(2, 3, 'plotly.png', {'image_data': image_data})

# Create a new worksheet and add the image to it.
worksheet = workbook.add_worksheet()
worksheet.insert_image(2, 3, 'plotly.png', {'image_data': image_data})

# Close the Pandas Excel writer and output the Excel file.
writer.save()
Run Code Online (Sandbox Code Playgroud)

输出

在此输入图像描述

请注意,也可以直接在 Xlsxwriter 中从 Pandas 数据帧绘制图表。请参阅XlsxWriter 文档的将图表添加到数据帧输出部分。