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

Python - วาด Pie Chart ใน Excel ด้วย XlsxWriter

Pie chart (กราฟวงกลม) เป็นกราฟสถิติวงกลมแบ่งเป็นสไลด์ แสดงสัดส่วนตัวเลข ความยาวโค้งของแต่ละสไลด์สัมพันธ์กับปริมาณที่แทน

ตัวอย่างโค้ด


import xlsxwriter

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

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

headings = ['Category', 'Values']
data = [
    ['Apple', 'Cherry', 'Pecan'],
    [60, 30, 10],
]

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

# สร้าง Pie Chart
chart1 = workbook.add_chart({'type': 'pie'})

chart1.add_series({
    'name': 'Pie sales data',
    'categories': ['Sheet1', 1, 0, 3, 0],
    'values': ['Sheet1', 1, 1, 3, 1],
})

chart1.set_title({'name': 'Popular Pie Types'})
chart1.set_style(10)  # สไตล์มีขอบสีขาวและเงา

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

Pie Chart Subtypes


chart = workbook.add_chart({'type': 'pie'})                    # Basic pie
chart = workbook.add_chart({'type': 'pie', 'subtype': 'pie_of_pie'})      # Pie of Pie
chart = workbook.add_chart({'type': 'pie', 'subtype': 'bar_of_pie'})      # Bar of Pie
chart = workbook.add_chart({'type': 'pie', 'subtype': 'exploded'})        # Exploded pie

การปรับแต่ง Pie Chart


chart1.add_series({
    'name': 'Sales',
    'categories': ['Sheet1', 1, 0, 3, 0],
    'values': ['Sheet1', 1, 1, 3, 1],
    'points': [
        {'fill': {'color': '#FF6B6B'}},  # สีแต่ละสไลด์
        {'fill': {'color': '#4ECDC4'}},
        {'fill': {'color': '#45B7D1'}},
    ],
    'data_labels': {
        'percentage': True,      # แสดง %
        'category': True,        # แสดงชื่อ
        'value': True,           # แสดงค่า
        'leader_lines': True,    # เส้นนำ
        'position': 'outside_end',  # ตำแหน่ง label
    },
})

แนวทางปฏิบัติที่ดี (Best Practices)

  • ใช้ได้สูงสุด 5-7 categories มากกว่านี้อ่านยาก
  • จัดเรียงจากใหญ่ไปเล็ก (หรือตามลำดับที่มีความหมาย)
  • หลีกเลี่ยง 3D pie chart (บิดเบือนการมองเห็น)
  • พิจารณา Bar chart แทนถ้าต้องการเปรียบเทียบค่าอย่างแม่นยำ
  • ใช้ "Pie of Pie" หรือ "Bar of Pie" สำหรับ categories มากมาย

ตัวอย่าง: Exploded Pie (ดึงสไลด์ออกมาเน้น)


chart1.add_series({
    'name': 'Sales',
    'categories': ['Sheet1', 1, 0, 3, 0],
    'values': ['Sheet1', 1, 1, 3, 1],
    'points': [
        {'explosion': 20},  # ดึงสไลด์แรกออก 20%
        {},
        {},
    ],
})