mongodb數據可視化_使用MongoDB實時可視化開放數據

mongodb數據可視化

Using Python to connect to Taiwan Government PM2.5 open data API, and schedule to update data in real time to MongoDB — Part 2

使用Python連接到臺灣政府PM2.5開放數據API,并計劃將數據實時更新到MongoDB —第2部分

目標 (Goal)

This time I’m using the same PM2.5 open data API (used in Part 1) to showcase how to refresh real time data into mongoDB for every 2 min (because it’s the time for the government’s portal to refresh its API). The strength of mongoDB is it’s simple to use, especially with JSON document format data. This makes connecting to open data much easier. Also we can directly show real time data changes from our database using its Charts & Dashboard features.

這次,我使用相同的PM2.5開放數據API(在第1部分中使用過)來展示如何每2分鐘將實時數據刷新到mongoDB中(因為這是政府門戶網站刷新其API的時間)。 mongoDB的優勢在于它易于使用,尤其是使用JSON文檔格式數據時。 這使得連接打開的數據變得更加容易。 我們還可以使用其“圖表和儀表板”功能直接從數據庫中顯示實時數據更改。

How convenient!

多么方便!

The below demo uses Taipei City (the capital city of Taiwan) as example:

下面的演示以臺北市(臺灣省會城市)為例:

Skills covered:

涵蓋技能:

  • Connect to API with required parameters to filter out all sensors data in Taipei City

    連接到具有所需參數的API,以過濾掉臺北市中的所有傳感器數據
  • Insert the first batch of data into mongoDB

    將第一批數據插入mongoDB
  • Set a schedule to extract new batch of PM2.5 data from API into mongoDB

    設置時間表以從API將新的PM2.5數據批次提取到mongoDB中
  • Create charts into dashboard

    將圖表創建到儀表板

So, let’s get started.

因此,讓我們開始吧。

處理 (Process)

Import all required libraries:

導入所有必需的庫:

# connect to mongoDB cloud cluster
import pymongo
from pymongo import MongoClient# convert timezone
import pytz, dateutil.parser# connect to government open data API
import requests

Connect to API with required parameters to filter out all sensors data in Taipei City. Raw data looks like below (total count of sensors is 100):

使用必需的參數連接到API,以過濾掉臺北市中的所有傳感器數據。 原始數據如下所示(傳感器總數為100):

Image for post

All data was stored in “first_batch” variable:

所有數據都存儲在“ first_batch”變量中:

# Parameters: the latest data, observation value > 0, PM2.5 data only, Taipei city
# https://sta.ci.taiwan.gov.tw/STA_AirQuality_EPAIoT/v1.0/Datastreams?$expand=Thing,Observations($top=1)&$filter=name eq'PM2.5' and Observations/result gt 0 and Thing/properties/city eq '臺北市'&$count=truedef API_data():API_URL = "https://sta.ci.taiwan.gov.tw/STA_AirQuality_EPAIoT/v1.0/Datastreams?$expand=Thing,Observations($top=1)&$filter=name%20eq%27PM2.5%27%20and%20Observations/result%20gt%200%20and%20Thing/properties/city%20eq%20%27%E8%87%BA%E5%8C%97%E5%B8%82%27&$count=true"total = requests.get(API_URL).json()data = total['value']first_batch = []for item in data:dic = {}dic['_id'] = item['Thing']['properties']['stationID']dic['name'] = item['name']dic['areaDescription'] = item['Thing']['properties']['areaDescription']dic['city'] = item['Thing']['properties']['city']dic['township'] = item['Thing']['properties']['township']dic['observedArea'] = item['observedArea']dic['iso8601_UTC_0'] = item['Observations'][0]['phenomenonTime']UTC_0 = dateutil.parser.parse(dic['iso8601_UTC_0'])dic['UTC_0'] = str(UTC_0)UTC_8 = UTC_0.astimezone(pytz.timezone("Asia/Taipei"))dic['UTC_8'] = str(UTC_8)dic['result'] = item['Observations'][0]['result']dic['unitOfMeasurement'] = item['unitOfMeasurement']['symbol']first_batch.append(dic)return first_batchfirst_batch = API_data()

The first value within “first_batch” list is a sensor station’s data read:

“ first_batch”列表中的第一個值是讀取的傳感器站數據:

print(first_batch[0])# output: 
{'_id': '10189360662', 'name': 'PM2.5', 'areaDescription': '營建混合物土資場', 'city': '臺北市', 'township': '北投區', 'observedArea': {'type': 'Point', 'coordinates': [121.4871916, 25.121195]}, 'iso8601_UTC_0': '2020-08-20T05:22:58.000Z', 'UTC_0': '2020-08-20 05:22:58+00:00', 'UTC_8': '2020-08-20 13:22:58+08:00', 'result': 22.0, 'unitOfMeasurement': 'μg/m3'}

Then connect to my mongoDB Atlas and insert the first batch of data:

然后連接到我的mongoDB Atlas并插入第一批數據:

# connect to my mongoDB cloud clustercluster = MongoClient("mongodb+srv://<username>:<password>@cluster0.dd7sd.mongodb.net/<dbname>?retryWrites=true&w=majority")# my database name
db = cluster["test"]# my collection's name
collection = db["test2"]results = collection.insert_many(first_batch)

Next, set a scheduler to pull out latest PM2.5 data read from API (every 2 min and stop at a time whenever we wanted) and update data by “_id” on mongoDB i.e. “stationID” of each station:

接下來,設置一個調度程序以提取從API讀取的最新PM2.5數據(每2分鐘一次,并在需要時停止一次),并在mongoDB上通過“ _id”更新數據,即每個站的“ stationID”:

import schedule
import time
import datetime
import sysdef update_content():# get a new batchnew_batch = API_data() for item in new_batch:update_data = {"iso8601_UTC_0": item['iso8601_UTC_0'], "UTC_0": item['UTC_0'], "UTC_8": item['UTC_8'], "result": item['result']}results = collection.update_one({"_id": item['_id']}, {"$set": update_data}, upsert=True)def stop_update():sys.exit()schedule.every(2).minutes.do(update_content)
schedule.every(5).minutes.do(stop_update)while True: schedule.run_pending() time.sleep(1)

In mongoDB it will look like this:

在mongoDB中,它將如下所示:

Image for post
PM2.5 intensity score was 19.47.
PM2.5強度得分是19.47。
Image for post
After 2 min, it became 20.16.
2分鐘后,它變成20.16。

Lastly, we created each charts on dashboard as following:

最后,我們在儀表板上創建了每個圖表,如下所示:

Image for post
Add new data source (my real time data is saved in collection “test2”).
添加新的數據源(我的實時數據保存在集合“ test2”中)。
Image for post
Create a new dashboard.
創建一個新的儀表板。
Image for post
Create a heat map.
創建一個熱圖。
Image for post
Once we drag the chart into dashboard, we can set auto-refresh feature on the dashboard. When our application is running in the background, updating data into mongoDB, our charts will then be updated accordingly.
將圖表拖入儀表板后,可以在儀表板上設置自動刷新功能。 當我們的應用程序在后臺運行時,將數據更新到mongoDB中,然后將相應地更新我們的圖表。
Image for post
We can also create a scatter plot with customized tooltips. We can see there was a construction site which may result in higher level of PM2.5.
我們還可以使用自定義工具提示創建散點圖。 我們看到有一個建筑工地,可能導致更高的PM2.5水平。
Image for post
Note that time series line chart’s date format need to be modified in customized tab.
請注意,需要在自定義標簽中修改時間序列折線圖的日期格式。
Image for post
We can also create a gauge chart (The maximum score of PM2.5 is 100.)
我們還可以創建一個量表(PM2.5的最高得分為100。)

結論 (Conclusion)

With the above 4 charts, our dashboard is ready:

有了以上4個圖表,我們的儀表板已準備就緒:

Image for post
Image for post

We can further modify the color according to the intensity level set by government e.g. in Taiwan, 0–30 μg/m3 is low, 30–50 μg/m3 is medium, etc. Below I set within 5 min, how much the PM2.5 intensity changed “slightly” across different sensors in Taipei City on both maps. This clip was recorded later than the previous demo, around 19:00–19:30, but still on the same day.

我們可以根據政府設定的強度水平進一步修改顏色,例如在臺灣,0–30μg/ m3低,30–50μg/ m3中度等。在5分鐘內低于我設定的PM2。在兩張地圖上,臺北市的不同傳感器上的5個強度“略有變化”。 該剪輯的錄制時間比上一個演示晚,大約在19:00–19:30,但仍在同一天。

At the left-bottom corner of scatter plot, it shows how much time left for mongoDB to refresh the data input again, or just stare at the below clip for 10 sec you may spot the difference :D

在散點圖的左下角,它顯示了mongoDB再次刷新數據輸入還有多少時間,或者只是盯著下面的剪輯10秒鐘,您可能會發現差異:D

Image for post
Recorded at 19:00–19:30 on Aug 20, 2020
記錄于2020年8月20日19:00–19:30

That’s it. Hope you find this helpful.

而已。 希望對您有所幫助。

Have a wonderful day!

祝你有美好的一天!

翻譯自: https://medium.com/li-ting-liao-tiffany/visualize-open-data-using-mongodb-in-real-time-2cca4bcca26e

mongodb數據可視化

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391621.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391621.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391621.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

4.kafka的安裝部署

為了安裝過程對一些參數的理解&#xff0c;我先在這里提一下kafka一些重點概念,topic,broker,producer,consumer,message,partition,依賴于zookeeper, kafka是一種消息隊列,他的服務端是由若干個broker組成的&#xff0c;broker會向zookeeper&#xff0c;producer生成者對應一個…

javascript初學者_針對JavaScript初學者的調試技巧和竅門

javascript初學者by Priyanka Garg由Priyanka Garg My intended audience for this tutorial is beginner programmers. You’ll learn about frustration-free debugging with chrome dev tools.本教程的目標讀者是初學者。 您將學習使用chrome開發工具進行無挫折的調試。 D…

leetcode 705. 設計哈希集合

不使用任何內建的哈希表庫設計一個哈希集合&#xff08;HashSet&#xff09;。 實現 MyHashSet 類&#xff1a; void add(key) 向哈希集合中插入值 key 。 bool contains(key) 返回哈希集合中是否存在這個值 key 。 void remove(key) 將給定值 key 從哈希集合中刪除。如果哈希…

ecshop 前臺個人中心修改側邊欄 和 側邊欄顯示不全 或 導航現實不全

怎么給個人中心側邊欄加項或者減項 在模板文件default/user_menu.lbi 文件里添加或者修改,一般看到頁面都會知道怎么加,怎么刪,這里就不啰嗦了 添加一個欄目以后,這個地址跳的頁面怎么寫 這是最基本的一個包括左側個人信息,頭部導航欄 <!DOCTYPE html PUBLIC "-//W3C//…

leetcode 706. 設計哈希映射

不使用任何內建的哈希表庫設計一個哈希映射&#xff08;HashMap&#xff09;。 實現 MyHashMap 類&#xff1a; MyHashMap() 用空映射初始化對象 void put(int key, int value) 向 HashMap 插入一個鍵值對 (key, value) 。如果 key 已經存在于映射中&#xff0c;則更新其對應…

數據庫語言 數據查詢_使用這種簡單的查詢語言開始查詢數據

數據庫語言 數據查詢Working with data is becoming an increasingly important skill in the modern workplace. 在現代工作場所中&#xff0c;處理數據已成為越來越重要的技能。 Data is no longer the domain of analysts and software engineers. With todays technology,…

面向對象編程思想-觀察者模式

一、引言 相信猿友都大大小小經歷過一些面試&#xff0c;其中有道經典題目&#xff0c;場景是貓咪叫了一聲&#xff0c;老鼠跑了&#xff0c;主人被驚醒&#xff08;設計有擴展性的可加分&#xff09;。對于初學者來說&#xff0c;可能一臉懵逼&#xff0c;這啥跟啥啊是&#x…

typescript 使用_如何使用TypeScript輕松修改Minecraft

typescript 使用by Josh Wulf通過喬什沃爾夫(Josh Wulf) 如何使用TypeScript輕松修改Minecraft (How to modify Minecraft the easy way with TypeScript) Usually, modifying Minecraft requires coding in Java, and a lot of scaffolding. Now you can write and share Min…

Python:在Pandas數據框中查找缺失值

How to find Missing values in a data frame using Python/Pandas如何使用Python / Pandas查找數據框中的缺失值 介紹&#xff1a; (Introduction:) When you start working on any data science project the data you are provided is never clean. One of the most common …

監督學習-回歸分析

一、數學建模概述 監督學習&#xff1a;通過已有的訓練樣本進行訓練得到一個最優模型&#xff0c;再利用這個模型將所有的輸入映射為相應的輸出。監督學習根據輸出數據又分為回歸問題&#xff08;regression&#xff09;和分類問題&#xff08;classfication&#xff09;&#…

leetcode 54. 螺旋矩陣(遞歸)

給你一個 m 行 n 列的矩陣 matrix &#xff0c;請按照 順時針螺旋順序 &#xff0c;返回矩陣中的所有元素。 示例 1&#xff1a; 輸入&#xff1a;matrix [[1,2,3],[4,5,6],[7,8,9]] 輸出&#xff1a;[1,2,3,6,9,8,7,4,5] 示例 2&#xff1a; 輸入&#xff1a;matrix [[1,…

微服務架構技能

2019獨角獸企業重金招聘Python工程師標準>>> 微服務架構技能 博客分類&#xff1a; 架構 &#xff08;StuQ 微服務技能圖譜&#xff09; 2課程簡介 本課程分為基礎篇和高級篇兩部分&#xff0c;旨在通過完整的案例&#xff0c;呈現微服務的開發、測試、構建、部署、…

phpstorm 調試_PhpStorm中的多用戶調試

phpstorm 調試by Ray Naldo雷納爾多(Ray Naldo) PhpStorm中的多用戶調試 (Multi-User Debugging in PhpStorm) 使用Xdebug和DBGp代理 (Using Xdebug and DBGp Proxy) “Er, wait a minute… Don’t you just use xdebug.remote_connect_back which has been introduced since …

Tableau Desktop認證:為什么要關心以及如何通過

Woah, Tableau!哇&#xff0c;Tableau&#xff01; By now, almost everyone’s heard of the data visualization software that brought visual analytics to the public. Its intuitive drag and drop interface makes connecting to data, creating graphs, and sharing d…

約束布局constraint-layout導入失敗的解決方案 - 轉

今天有同事用到了約束布局&#xff0c;但是導入我的工程出現錯誤 **提示錯誤&#xff1a; Could not find com.Android.support.constraint:constraint-layout:1.0.0-alpha3** 我網上查了一下資料&#xff0c;都說是因為我的androidStudio版本是最新的穩定版導入這個包就會報這…

算法復習:冒泡排序

思想&#xff1a;對于一個列表,每個數都是一個"氣泡 "&#xff0c;數字越大表示"越重 "&#xff0c;最重的氣泡移動到列表最后一位&#xff0c;冒泡排序后的結果就是“氣泡”按照它們的重量依次移動到列表中它們相應的位置。 算法&#xff1a;搜索整個列表…

leetcode 59. 螺旋矩陣 II(遞歸)

給你一個正整數 n &#xff0c;生成一個包含 1 到 n2 所有元素&#xff0c;且元素按順時針順序螺旋排列的 n x n 正方形矩陣 matrix 。 示例 1&#xff1a; 輸入&#xff1a;n 3 輸出&#xff1a;[[1,2,3],[8,9,4],[7,6,5]] 解題思路 按層進行數字的填充&#xff0c;每一層…

前端基礎進階(七):函數與函數式編程

縱觀JavaScript中所有必須需要掌握的重點知識中&#xff0c;函數是我們在初學的時候最容易忽視的一個知識點。在學習的過程中&#xff0c;可能會有很多人、很多文章告訴你面向對象很重要&#xff0c;原型很重要&#xff0c;可是卻很少有人告訴你&#xff0c;面向對象中所有的重…

期權數據 獲取_我如何免費獲得期權數據

期權數據 獲取by Harry Sauers哈里紹爾斯(Harry Sauers) 我如何免費獲得期權數據 (How I get options data for free) 網頁抓取金融簡介 (An introduction to web scraping for finance) Ever wished you could access historical options data, but got blocked by a paywall…

顯示與刪除使用工具

右擊工具菜單欄中的空白處選擇自定義 在彈出的自定義菜單中選擇命令選項在選擇想要往里面添加工具的菜單&#xff0c;之后在選擇要添加的工具 若想要刪除工具欄中的某個工具&#xff0c;在打開自定義菜單后&#xff0c;按住鼠標左鍵拖動要刪除工具到空白處 例如 轉載于:https:/…