Scatter plot (กระจายจุด) เป็นกราฟที่ใช้พิกัด Cartesian แสดงค่าของตัวแปรสองตัวสำหรับชุดข้อมูล หากจัดสีจุด สามารถแสดงตัวแปรที่สามได้อีกด้วย
ตัวอย่างโค้ด
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_scatter.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
headings = ['Number', 'Batch 1', 'Batch 2']
data = [
[2, 3, 4, 5, 6, 7],
[80, 80, 100, 60, 50, 100],
[60, 50, 60, 20, 10, 20],
]
# เขียนข้อมูล
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])
# สร้าง Scatter Chart
chart1 = workbook.add_chart({'type': 'scatter'})
# Series แรก
chart1.add_series({
'name': '=Sheet1!$B$1',
'categories': '=Sheet1!$A$2:$A$7',
'values': '=Sheet1!$B$2:$B$7',
})
# Series ที่สอง (ใช้ syntax แบบ array)
chart1.add_series({
'name': ['Sheet1', 0, 2],
'categories': ['Sheet1', 1, 0, 6, 0],
'values': ['Sheet1', 1, 2, 6, 2],
})
# ตั้งค่ากราฟ
chart1.set_title({'name': 'Results of data analysis'})
chart1.set_x_axis({'name': 'Test number'})
chart1.set_y_axis({'name': 'Data length (mm)'})
chart1.set_style(11)
worksheet.insert_chart('E2', chart1)
workbook.close()
Scatter Chart Subtypes ใน XlsxWriter
# Subtypes ต่างๆ
chart = workbook.add_chart({'type': 'scatter', 'subtype': 'straight'}) # เส้นตรง
chart = workbook.add_chart({'type': 'scatter', 'subtype': 'straight_with_markers'}) # เส้นตรง+จุด
chart = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth'}) # เส้นโค้ง
chart = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth_with_markers'}) # เส้นโค้ง+จุด
chart = workbook.add_chart({'type': 'scatter'}) # Default: markers only
การกำหนดช่วงข้อมูล (Range Specification)
XlsxWriter รองรับ 2 รูปแบบ:
- A1 notation:
'=Sheet1!$A$2:$A$7' - List notation:
['Sheet1', 1, 0, 6, 0]→ [sheetname, first_row, first_col, last_row, last_col] (0-indexed)
การปรับแต่ง Marker
chart1.add_series({
'name': '=Sheet1!$B$1',
'categories': '=Sheet1!$A$2:$A$7',
'values': '=Sheet1!$B$2:$B$7',
'marker': {
'type': 'circle', # circle, square, diamond, triangle, etc.
'size': 8,
'border': {'color': 'black'},
'fill': {'color': 'red'},
},
'line': {'none': True}, # ไม่แสดงเส้นเชื่อม
})
สรุป
- Scatter chart เหมาะสำหรับแสดงความสัมพันธ์ระหว่างตัวแปรสองตัว
- ใช้
subtypeเลือกรูปแบบเส้น/จุด - ระบุช่วงข้อมูลได้ 2 รูปแบบ: A1 notation หรือ List notation
- ปรับแต่ง marker และ line ได้ละเอียด