【问题标题】:Using pandas excel workbook to create pie chart from 1 column使用 pandas excel 工作簿从 1 列创建饼图
【发布时间】:2021-02-01 22:38:27
【问题描述】:

我正在尝试从 DF 中的列创建一个 excel 饼图,该列有 2 个重复多次的值(“PASS,FAIL”)。

我想要一个饼图来显示通过次数和失败次数

excel_file = 'pie.xlsx'
sheet_name = 'Sheet1'
writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
df.to_excel(writer, sheet_name=sheet_name)
df.to_excel("output.xlsx")
workbook = writer.book
worksheet = writer.sheets[sheet_name]
chart = workbook.add_chart({'type': 'pie'})
chart.add_series({
    'categories': '=Sheet1!D2:D233',
    'values':     '=Sheet1\'Total Counts\'D2:D233'
})
worksheet.insert_chart('G2', chart)
writer.save()

代码生成一个空白饼图

【问题讨论】:

    标签: python excel pandas charts


    【解决方案1】:

    您无法在 Excel 中根据一系列值绘制饼图并将它们分组为匹配的类别和值。相反,您可能必须添加一些总和/计数公式并绘制这些结果。

    这是一个基于您的小型工作示例:

    import pandas as pd
    from xlsxwriter.utility import xl_range
    
    # Create a Pandas dataframe from some data.
    df = pd.DataFrame({'Data': ['Fail', 'Pass', 'Fail', 'Pass', 'Pass']})
    
    # Convert the dataframe to an Excel file.
    excel_file = 'pie.xlsx'
    sheet_name = 'Sheet1'
    writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
    df.to_excel(writer, sheet_name=sheet_name)
    
    # Get the max row number for the dataframe.
    max_row = len(df)
    cell_range = xl_range(1, 1, max_row, 1)
    
    # Access the Pandas xlsxwriter Excel file.
    workbook = writer.book
    worksheet = writer.sheets[sheet_name]
    
    # Write some text to act as chart category labels.
    worksheet.write('D2', "Pass");
    worksheet.write('D3', "Fail");
    
    # Count the instances of Pass/Fail to act as chart values.
    worksheet.write_formula('E2', '=COUNTIF(%s, "Pass")' % cell_range);
    worksheet.write_formula('E3', '=COUNTIF(%s, "Fail")' % cell_range);
    
    # Create a Pie chart.
    chart = workbook.add_chart({'type': 'pie'})
    
    # Add the chart series.
    chart.add_series({
        'categories': '=Sheet1!D2:D3',
        'values':     '=Sheet1!E2:E3'
    })
    
    # Insert the chart.
    worksheet.insert_chart('A8', chart)
    
    writer.save()
    

    输出

    【讨论】:

      【解决方案2】:

      这里用一个简单的例子来做:

      df = pd.DataFrame({'col1': [120, 216 , 72],'col2': [12, 24, 48]},index=['A', 'B', 'C'])
      plot = df.plot.pie(y='col1', figsize=(5, 5))
      

      输出:

      【讨论】:

      • 感谢您的建议,但我试图在 Excel 表本身内形成图表。有没有办法用 matploit 做到这一点?
      • 好吧,没关系。不要忘记关闭您的工作簿,因此使用 workbook.close() 来关闭您的 xls。您应该在tutorialspoint.com/…stackoverflow.com/questions/46227040/… 那里找到解决方案
      猜你喜欢
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 2020-08-19
      相关资源
      最近更新 更多