python编程:利用openpyxl 创建直方图实现函数,输入起始行号列号快捷创建

参考openpyxl的库文档创建直方图,但例程缺乏数据范围的明确说明,让人不知如何填入数据的行列,因此做了通用函数封装
官方文档实现
from openpyxl import Workbook
from openpyxl.chart import (
BarChart,
Reference,
Series,
) w
b = Workbook()
ws = wb.active
rows = [
['Number', 'Batch 1', 'Batch 2'],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10],
] f
or row in rows:
ws.append(row)
chart = BarChart()
chart.title = "Bar Chart"
chart.style = 10
chart.x_axis.title = 'Test'
chart.y_axis.title = 'Percentage'
cats = Reference(ws, min_col=1, min_row=1, max_row=7)
data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=7)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
ws.add_chart(chart, "A10")
wb.save("BarChart.xlsx")
我的封装实现,实测可行
import openpyxl
from openpyxl.chart import BarChart, Series, Reference
def Bar_Chart(start_row_data, end_row_data, start_col_data, end_col_data):
    wb = openpyxl.Workbook()
    ws = wb.active
    rows = [
        ('Number', 'Batch 1', 'Batch 2'),
        (2, 10, 30),
        (3, 40, 60),
        (4, 50, 70),
        (5, 20, 10),
        (6, 10, 40),
        (7, 50, 30),
    ]
    for row in rows:
        ws.append(row)
    chart1 = BarChart()
    chart1.type = "col"
    chart1.style = 10
    chart1.title = "Bar Chart"
    chart1.y_axis.title = 'Test number'
    chart1.x_axis.title = 'Sample length (mm)'
    data = Reference(ws, min_col=start_col_data + 1, min_row=start_row_data, max_row=end_row_data, max_col=end_col_data)
    cats = Reference(ws, min_col=start_col_data, min_row=start_row_data + 1, max_row=end_row_data)
    chart1.add_data(data, titles_from_data=True)
    chart1.set_categories(cats)
    chart1.shape = 4
    ws.add_chart(chart1, "A10")
    wb.save("barchar.xlsx")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值