【问题标题】:Python Pandas xlsxriter stacked line chart type setting standard line chart in ExcelPython Pandas xlsxwriter 堆积折线图类型设置Excel中的标准折线图
【发布时间】:2021-07-09 07:31:20
【问题描述】:

我正在尝试使用 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 堆叠,以前有人遇到过这个问题吗?

请注意我正在使用的版本:

  • Microsoft Office 365 Excel 2008 版。
  • print(pd.version) 输出:0.23.0

【问题讨论】:

    标签: python excel pandas xlsxwriter


    【解决方案1】:

    代码应该按预期工作。这是我运行它时的输出:

    请注意,XlsxWriter version 1.2.9 中添加了堆叠线支持,因此请确保您拥有该版本或更新版本。

    【讨论】:

    • 我的错,我有一个过时的熊猫版本,因此可能是 XLXSWriter。感谢您的帮助!
    • 没问题。只是关于那个例子的一些注释。您可能应该将“日期时间”字符串转换为实际的日期时间对象。就目前而言,Excel 将它们绘制为字符串。类别和值范围也不匹配。它们应该来自第 2 行而不是第 1 行。此外,根据 DataFrame 大小/形状,对值和类别使用列表语法可能会更好。例如:xlsxwriter.readthedocs.io/example_pandas_chart_line.html
    • 这非常有用,我会确保将这些做法纳入我的代码!
    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多