pandas 進行excel繪圖


python主流繪圖工具:matplotlib ,seaborn,pandas ,openpyxl ,xslwriter

openpyxl :首先說下這個官網的demo,看的有點懵,沒有具體說明多個圖在一個excel引用不通ws Rererence 只是簡單的一個deepcopy 用的一點懵逼,反正我是沒看懂,其次多sheet寫入也未做拓展,

看了下博客哪些水軍一篇粘貼復制毫無新意:

下面以openpyxl 3d bar 柱狀圖為例:演示效果多sheet 生成柱狀圖:

官網:https://openpyxl.readthedocs.io/en/latest/charts/bar.html#d-bar-charts

from openpyxl import Workbook
from openpyxl.chart import (
    Reference,
    Series,
    BarChart3D,
)


def bar_3d(configurations: dict):
    """"
    paint 3d bar in the excel ,
    configuration={"data":None,"Title":None,"sheet_name":None,"index":None}
    data:[
    [姓名,column1,column2],
    [value_name,value_col1,value_col2],
    [value_name2,value_column2,value_column2]
    ]
    """
    wb = Workbook()
    for configuration in configurations:
        sheet = configuration["sheet_name"]
        ws = wb.create_sheet(sheet, index=configuration["index"])
        rows = configuration["data"]
        rows.insert(0, configuration["axis_x"])
        for row in rows:
            ws.append(row)
        data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=7)
        titles = Reference(ws, min_col=1, min_row=2, max_row=7)
        chart = BarChart3D()
        chart.title = configuration["Title"]
        chart.add_data(data=data, titles_from_data=True)
        chart.set_categories(titles)
        chart.height=16
        chart.width=28
        chart.shape="box"

        ws.add_chart(chart, "E5")
    save_path = "test_static.xlsx"
    wb.save(save_path)

  解釋參數:configurations 是一個存放許多configranition 的列表:每個configration 結構如注釋:

configuration={"data":None,"Title":None,"sheet_name":None,"index":None}
    data:[
    
    [value_name,value_col1,value_col2],
    [value_name2,value_column2,value_column2]
    ]
data就是要寫入的數據包含header 和value,data[0]是表頭,data[1:]全部是數據,index代表插入excel的sheet的index也就是第幾個sheet,Title是繪制柱狀圖的title:
chart.height是圖表的高度,width是寬度,add_chart 是插入chart 方法“E5"指定在excel插入位置,
rows.insert(0, configuration["axis_x"]) 這里插入是type分類的名稱也就是rows.insert(0,[姓名,column1,column2])
,看個實際效果吧這個type就對應周日飽和,和bug提交量兩列

 多個sheet查看:

 

 

 第二部分:使用pandas 繪圖結合xslwriter:

官網:https://xlsxwriter.readthedocs.io/example_pandas_chart_columns.html

我就直接上代碼了數據自己造了個用pandas:

import pandas as pd


def panda_chart(df_list, cols, title_x, title_y):
    """
    data of narray
    index of data_frame:  [0,1,2,3]
    cols numbers of static columns
    """

    writer = pd.ExcelWriter('pandas_chart_columns2.xlsx', engine='xlsxwriter')
    for i, df in enumerate(df_list):
        # df = pd.DataFrame(data, index=None, columns=["姓名", "飽和度", "人力"])
        sheet_name = f'Sheet{i}'
        df.to_excel(writer, sheet_name=sheet_name,index=False)
        workbook = writer.book
        worksheet = writer.sheets[sheet_name]
        chart = workbook.add_chart({'type': 'column'})
        # set colors for the chart each type .
        colors = ['#E41A1C', '#377EB8']  # , '#4DAF4A', '#984EA3', '#FF7F00']
        # Configure the series of the chart from the dataframe data.
        for col_num in range(1, cols + 1):
            chart.add_series({
                'name':       [f'{sheet_name}', 0, col_num],
                'categories': [f'{sheet_name}', 1, 0, 4, 0],  # axis_x start row ,start col,end row ,end col
                'values':     [f'{sheet_name}', 1, col_num, 4, col_num],  # axis_y value of
                'fill':       {'color':  colors[col_num - 1]},  # each type color choose
                'overlap': -10,
            })

        # Configure the chart axes.
        chart.set_x_axis({'name': f'{title_x}'})
        chart.set_y_axis({'name': f'{title_y}', 'major_gridlines': {'visible': False}})
        chart.set_size({'width': 900, 'height': 400})
        # Insert the chart into the worksheet.
        worksheet.insert_chart('H2', chart)
    writer.save()

if __name__ == '__main__':
    data=[("a",2,4),("b",5,7)]
    df = pd.DataFrame(data, index=None, columns=["姓名", "飽和度", "人力"])
    panda_chart([df],2,"title x","title y")

  

 

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM