> For the complete documentation index, see [llms.txt](https://krootee.gitbook.io/python_datascience/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://krootee.gitbook.io/python_datascience/1..md).

# 1.แสดงกราฟจากข้อมูล

```
create code python barchart
      Math    science        thai    eng
AA     25         25          45      53
BB     45         65          35      93   
CC     42         61          32      45
```

```python
import matplotlib.pyplot as plt
import numpy as np

# ข้อมูลที่ให้มา
categories = ['Math', 'Science', 'Thai', 'English']
students = ['AA', 'BB', 'CC']
scores = {
    'AA': [25, 25, 45, 53],
    'BB': [45, 65, 35, 93],
    'CC': [42, 61, 32, 45]
}

# สร้างพื้นที่ในการวาดกราฟ
fig, ax = plt.subplots()

# ระยะห่างระหว่างกลุ่มแท่ง
bar_width = 0.2
index = np.arange(len(categories))

# วาดแท่งสำหรับแต่ละนักเรียน
for i, student in enumerate(students):
    bars = ax.bar(index + i * bar_width, scores[student], bar_width, label=student)

# กำหนดชื่อแกน X, Y และชื่อกราฟ
ax.set_xlabel('Subjects')
ax.set_ylabel('Scores')
ax.set_title('Student Scores by Subject')
ax.set_xticks(index + bar_width)
ax.set_xticklabels(categories)
ax.legend()

# แสดงกราฟ
plt.tight_layout()
plt.show()
```

> #### คำอธิบายโค้ด:
>
> 1. **การนำเข้าไลบรารี**:
>    * `import matplotlib.pyplot as plt`: นำเข้า `matplotlib.pyplot` ซึ่งเป็นเครื่องมือในการสร้างกราฟ
>    * `import numpy as np`: นำเข้า `numpy` ใช้สำหรับการคำนวณทางคณิตศาสตร์และการจัดการข้อมูล
> 2. **กำหนดข้อมูล**:
>    * `categories` เป็นรายการของวิชาที่เราต้องการให้แสดงบนแกน X
>    * `students` เป็นรายการของนักเรียน
>    * `scores` เป็นดิกชันนารีที่เก็บคะแนนของแต่ละนักเรียนในแต่ละวิชา
> 3. **การสร้างกราฟ**:
>    * `fig, ax = plt.subplots()`: สร้างพื้นที่ในการวาดกราฟ
>    * `bar_width = 0.2`: ระยะห่างระหว่างกลุ่มแท่ง
>    * `index = np.arange(len(categories))`: สร้างช่วงที่ใช้ในการจัดตำแหน่งแท่ง
> 4. **การวาดแท่ง**:
>    * ใช้ `ax.bar` ในการวาดแท่ง สำหรับแต่ละนักเรียน โดยการจัดตำแหน่งแท่งตามระยะห่างที่กำหนด
> 5. **การตั้งค่าต่างๆ**:
>    * `ax.set_xlabel`, `ax.set_ylabel`, `ax.set_title`: ตั้งชื่อแกน X, Y และชื่อกราฟ
>    * `ax.set_xticks`, `ax.set_xticklabels`: กำหนดตำแหน่งและชื่อของป้ายบนแกน X
>    * `ax.legend()`: แสดงตำนานของกราฟ
> 6. **การแสดงกราฟ**:
>    * `plt.tight_layout()`: ปรับพื้นที่กราฟให้พอดี
>    * `plt.show()`: แสดงกราฟ
