Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - วาด Excel Chart ด้วย Gradient Fills ด้วย XlsxWriter

XlsxWriter เป็นไลบรารี Python สำหรับทำงานกับ Excel: สร้าง เขียน คำนวณ และวาดกราฟ

ตัวอย่างโค้ด: Column Chart พร้อม Gradient Fill


import xlsxwriter

workbook = xlsxwriter.Workbook('chart_gradient1.xlsx')
worksheet = workbook.add_worksheet()

bold = workbook.add_format({'bold': 1})

headings = ['Number', 'Batch 1', 'Batch 2']
data = [
    [2, 3, 4, 5, 6, 7],
    [10, 40, 50, 20, 10, 50],
    [30, 60, 70, 50, 40, 30],
]

worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])

# สร้าง Column Chart
chart = workbook.add_chart({'type': 'column'})

# Series 1: Gradient
chart.add_series({
    'name': '=Sheet1!$B$1',
    'categories': '=Sheet1!$A$2:$A$7',
    'values': '=Sheet1!$B$2:$B$7',
    'gradient': {'colors': ['#963735', '#F1DCDB']},
})

# Series 2: Gradient
chart.add_series({
    'name': '=Sheet1!$C$1',
    'categories': '=Sheet1!$A$2:$A$7',
    'values': '=Sheet1!$C$2:$C$7',
    'gradient': {'colors': ['#E36C0A', '#FCEADA']},
})

chart.set_title({'name': 'Chart With Gradient Fills'})
chart.set_x_axis({'name': 'Test number'})
chart.set_y_axis({'name': 'Sample length (mm)'})
chart.set_legend({'none': True})

worksheet.insert_chart('D2', chart, {'x_offset': 25, 'y_offset': 10})
workbook.close()

Gradient Fill Properties


'gradient': {
    'colors': ['#963735', '#F1DCDB'],  # List of colors (2+ colors)
    # 'positions': [0, 1],             # Optional: ตำแหน่งสี (0-1)
    # 'angle': 90,                     # Optional: มุม (0-360)
}

Gradient Types

  • 2-color gradient: ระบุ 2 สี (ค่าเริ่มต้น)
  • Multi-color gradient: ระบุ 3+ สี พร้อม positions

ตัวอย่าง Multi-color Gradient


chart.add_series({
    'values': '=Sheet1!$B$2:$B$7',
    'gradient': {
        'colors': ['#FF0000', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF'],
        'positions': [0, 0.25, 0.5, 0.75, 1.0],
    },
})

Pattern vs Gradient Fill

Pattern FillGradient Fill
48 รูปแบบคงที่สีไล่ระดับ (smooth transition)
เหมาะพิมพ์ขาวดำเหมาะหน้าจอ/สไลด์สี
Accessibility ดีดูทันสมัย สวยงาม
fg/bg colorcolors array + positions

การปรับแต่งเพิ่มเติม


# Border กับ Gradient
chart.add_series({
    'values': '=Sheet1!$B$2:$B$7',
    'gradient': {'colors': ['#4472C4', '#FFFFFF']},
    'border': {'color': '#2F5496', 'width': 1.5},
})

# Gradient บน Line Chart
chart = workbook.add_chart({'type': 'line'})
chart.add_series({
    'values': '=Sheet1!$B$2:$B$7',
    'line': {
        'color': '#4472C4',
        'gradient': {'colors': ['#4472C4', '#FFFFFF']},
    },
})

สรุป

  • ใช้ gradient property ใน add_series()
  • ระบุ colors array (2+ สี) และ positions (optional)
  • ใช้ได้กับ Column, Bar, Area, Line, Pie, Doughnut
  • ดูทันสมัย สวยงาม เหมาะสำหรับ Dashboard และ Presentation
  • ปิด Legend (set_legend({'none': True})) ถ้ามี Series เดียวหรือ Label ชัดเจน