我正在尝试使用 pandas 和 xlsxwriter 在 excel 中创建堆叠折线图。
将图表类型 dict 输入添加图表时,我使用文档状态应在 Excel 中配置堆积线。 (所以我想无论如何!)当我打开 Excel 时,我得到一个标准折线图,这意味着我需要手动更改为堆叠线(第二个跨框)
这是一些示例代码
import pandas as pd
# example csv data
'''
Date-Time col1 col2
2021-03-01 00:00:00 34329 34540
2021-03-01 00:15:00 34174 34369
2021-03-01 00:30:00 34121 34418
2021-03-01 00:45:00 34012 34235
2021-03-01 01:00:00 33959 34273
2021-03-01 01:15:00 33825 34049
2021-03-01 01:30:00 33782 34010
2021-03-01 01:45:00 33584 33882
2021-03-01 02:00:00 33601 33905
2021-03-01 02:15:00 33415 33746
2021-03-01 02:30:00 33412 33827
2021-03-01 02:45:00 33291 33744
2021-03-01 03:00:00 33329 33816
2021-03-01 03:15:00 33209 33745
2021-03-01 03:30:00 33219 33833
'''
# create df
with open('example.csv', 'r') as csv:
df = pd.read_csv(csv).set_index('Date-Time')
# Create the workbook to save the data within
workbook = pd.ExcelWriter('example.xlsx', engine='xlsxwriter')
# Create sheets in excel for data
pd.DataFrame().to_excel(workbook, sheet_name='Dashboard')
# assign a blank dashboard for the charts
worksheet_dashboard = workbook.sheets['Dashboard']
# Get the xlsxwriter objects from the dataframe writer object
# for use with creating charts later
book = workbook.book
# Create sheets in excel for data
df.to_excel(workbook, sheet_name='example')
# Add the line chart objects
chart = book.add_chart({'type': 'line', 'subtype': 'stacked'})
# Configure the first series.
chart.add_series({
'name': '=example!$B$1',
'categories': '=example!$A$1:$A$16',
'values': '=example!$B$2:$B$16',
})
chart.add_series({
'name': '=example!$C$1',
'categories': '=example!$A$1:$A$16',
'values': '=example!$C$2:$C$16',
})
# Insert the chart into the worksheet
worksheet_dashboard.insert_chart('A1', chart)
workbook.save()
你可以看到这条线# Add the line chart objects
chart = book.add_chart({'type': 'line', 'subtype': 'stacked'})
应该提供类型为 line 和 subtype 堆叠,以前有人遇到过这个问题吗?请注意,我正在使用的版本:
最佳答案
代码应该按预期工作。这是我运行它时的输出:
注意,在 XlsxWriter version 1.2.9 中添加了堆叠线支持。因此,请确保您拥有该版本或更新版本。
关于Python Pandas xlsxwriter 堆积折线图类型设置Excel中的标准折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67088524/