# Matplotlib統計圖表繪製

Matplotlib是Python中非常受到歡迎的圖表繪製模組，以下是它的官網，在官網中就可以看出它的能力是多麼強大：

{% embed url="<https://matplotlib.org/>" %}

儘管它的功能強大，但在使用上確是非常簡單，基本上只要有兩個座標串列的資料，送進去plot函數中，即可幫我們繪製出圖表，在jupyter notebook使用Matplotlib繪製圖表的基本程式如下：

```python
%matplotlib inline
import matplotlib.pyplot as plt
temperatures = [32.1, 33.5, 33.6, 33.7, 34.9, 34.9, 35, 35.1, 35.5, 36.3, 36.4, 36.5, 36.5, 36.4, 36.3]
plt.plot(range(len(scores)), temperatures)
plt.show()
```

上述程式中的第3行是某一個時段量測到的即時溫度資料，想要把溫度變化的情形畫出來，只要把這些溫度資料放到第4行中的第2個參數中（Y座標值），而在第1個參數中放的是X座標值，最後再以plt.show() 函數即可呈現出該圖形。第1行的目的是為了告訴jupyter notebook把此圖形嵌入到輸出區域即可。繪製出來的圖形如下所示：

![](/files/-Le6epn1DBB9Ds-fhB_g)

如果想要比較兩組不同的數組，例如在不同的月份的同一段時間之溫度變化情形，可以準備這個組數列，各使用一個plt.plot()函數呼叫，最後再用1個plt.show()把它們一併呈現出來即可，程式如下所示：

```python
%matplotlib inline
import matplotlib.pyplot as plt
temper1 = [32.1, 33.5, 33.6, 33.7, 34.9, 34.9, 35, 35.1, 35.5, 36.3, 36.4, 36.5, 36.5, 36.4, 36.3]
temper2 = [25.1, 25.5, 25.6, 25.6, 26.2, 26.3, 26, 26.1, 25.5, 25.3, 25.4, 25.2, 25.1, 25, 24.5]
plt.plot(range(len(scores)), temper1)
plt.plot(range(len(scores)), temper2)
plt.show()
```

在同一張圖表中使用了2個數組，matplotlib會自動使用不同的顏色來繪製，結果如下：

![](/files/-Le6gObBgn_eVtKzpM1W)

當然，如果要加上標頭名稱以及x, y座標的說明以及圖例，也都有相對應的函數可以使用，如下：

```python
%matplotlib inline
import matplotlib.pyplot as plt
temper1 = [32.1, 33.5, 33.6, 33.7, 34.9, 34.9, 35, 35.1, 35.5, 36.3, 36.4, 36.5, 36.5, 36.4, 36.3]
temper2 = [25.1, 25.5, 25.6, 25.6, 26.2, 26.3, 26, 26.1, 25.5, 25.3, 25.4, 25.2, 25.1, 25, 24.5]
plt.title("Temperature: June vs. March")
plt.xlabel("Measurement")
plt.ylabel("degree")
plt.ylim(20, 45)
plt.plot(range(len(scores)), temper1, label='June')
plt.plot(range(len(scores)), temper2, label='March')
plt.legend()
plt.show()
```

上述程式執行的結果如下所示：

![](/files/-Le6hoOLIe9vVBj79Yfi)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nkust.gitbook.io/python/matplotlib-biao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
