Python:如何在同一图表中绘制来自不同 excel 工作表的数据

Python: how to plot data coming from different excel sheets in the same chart

我需要在 python 上创建一个交互式图表,从 Excel 文件的不同 sheet 中获取数据。我试图创建一个 for 循环以自动从所有 sheet 中获取数据,但我设法仅绘制来自文件最后一个 sheet 的数据。 我还想创建一个图例,其中包含数据来源的 sheet 的名称。这是我的代码,你能帮我改进一下吗?

import openpyxl as xl
import os, os.path
import pandas as pd
import plotly.express as px

output_data2=r'C:\Users\Desktop\Vibration data analysis'

wb=xl.load_workbook(os.path.join(output_data2, "RMS Comparison.xlsx"))
for sheet in wb.worksheets:
    if sheet.title != 'Graph':
        df = pd.read_excel(os.path.join(output_data2, "RMS Comparison.xlsx"),sheet_name=sheet.title)
        fig = px.line(df, x='Unnamed: 0', y='Unnamed: 2')
fig.show()
  • 已经模拟了一个工作簿来演示plotly代码
  • 创建一个图形,然后为每个工作表添加一行
import openpyxl as xl
from pathlib import Path
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go

f = Path.cwd().joinpath("RMS Comparison.xlsx")

# create an Excel with multiple sheets
with pd.ExcelWriter(f) as writer: 
    for s in "ABCDEF":
        pd.DataFrame({c:np.random.randint(1,10,30) if c[-1]!="0" else np.linspace(1,20, 30) for c in ['Unnamed: 0', 'Unnamed: 2']}).to_excel(writer, sheet_name=s)

# create a figure with a line per worksheet
wb=xl.load_workbook(f)
fig = go.Figure()
for sheet in wb.worksheets:
    if sheet.title != 'Graph':
        df = pd.read_excel(f,sheet_name=sheet.title)
        fig = fig.add_traces(px.line(df, x='Unnamed: 0', y='Unnamed: 2').update_traces(name=sheet.title, showlegend=True).data)

fig.show()