> For the complete documentation index, see [llms.txt](https://nkust.gitbook.io/nodemcu/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nkust.gitbook.io/nodemcu/nodemcu/shi-yong-python-cheng-shi-ji.md).

# 使用Python程式即時繪製數據圖檔

{% hint style="info" %}
要在Python中繪製圖表，最常用的套件是 matplotlib

如果要進行資料分析，通常都是使用 pandas

要下載網頁的資料的話，我們使用的是 requests

處理 JSON 資料格式，當然是用 json
{% endhint %}

運用ThingSpeak上的資料有兩種常見的方式，第一種是到「 Import/Export」頁籤中去下載所有的資料回來，它會以CSV（以逗號分隔的資料，可以使用Excel讀取）的方式儲存到我們的磁碟中，我們的程式再載入此檔案加以分析。

而其實，每一個公開的Channel也可以透過下載的方式，隨時的取得最近的100筆資料，如果你要的資料只是最近的資料，那麼使用此種方式是最方便的。

要在網路上即時讀取最近的資料，需要先設定為「Public View」，就可以網頁中看到要讀取的網址，透過該網址就可以在瀏覽器看到該格式的資料，以JSON格式為例，原始資料如下（網址：<https://thingspeak.com/channels/630561/feed.json）：>

![](/files/-LSCBkhamV349eKjpQ6N)

我們的做法是透過該網址把這筆資料下載到變數中，然後再透過json模組把原有的json格式的資料轉換成Python語言中的字典dict型態，接著再把我們想要的內容放到Pandas的DataFrame資料結構中就可以開始整理資料，或是把資料繪製成圖表了。

以下是程式碼：

```python
%matplotlib inline
import pandas as pd
import requests
import json

url = 'https://thingspeak.com/channels/630561/feed.json'
data = requests.get(url).text
jdata = json.loads(data)
feeds = jdata['feeds']
df = pd.DataFrame(feeds)
temperature = pd.to_numeric(df['field1'])
temperature.plot()
humidity = pd.to_numeric(df['field2'])
humidity.plot()
```

{% hint style="info" %}
請留意，上述的程式碼是在Jupyter notebook環境中執行的。
{% endhint %}

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

![](/files/-LSA_mybwxNnrcnYpq2C)

在預設的情形下，每一次畫圖的內容都會被放在同一張圖表中，如果你只是要看其中一個圖表（例如溫度），那麼只要先把另一個圖表的繪圖部份先註解起來就可以了，程式碼可以修改如下：

```python
%matplotlib inline
import pandas as pd
import requests
import json

url = 'https://thingspeak.com/channels/630561/feed.json'
data = requests.get(url).text
jdata = json.loads(data)
feeds = jdata['feeds']
df = pd.DataFrame(feeds)
temperature = pd.to_numeric(df['field1'])
temperature.plot()
#humidity = pd.to_numeric(df['field2'])
#humidity.plot()
```

此時的輸出圖表就會只呈現溫度的部份：

![](/files/-LSAaRQ9DdtgBGHuQLtI)
