利用python繪制數(shù)據(jù)曲線圖的實(shí)現(xiàn)
”在舉國上下萬眾一心、眾志成城做好新冠肺炎疫情防控工作的特殊時刻,我們不能親臨主戰(zhàn)場,但我們能堅(jiān)持在大戰(zhàn)中堅(jiān)定信心、不負(fù)韶華?!?/p>
1、爬取新聞保存為json文件,并將繪圖所需數(shù)據(jù)保存至數(shù)據(jù)庫
數(shù)據(jù)庫表結(jié)構(gòu):

代碼部分:
import pymysql
import re
import sys,urllib,json
from urllib import request
from datetime import datetime
import pandas as pd
Today=datetime.now().strftime(r"%Y-%m-%d")
#Today='2020-02-14'
def pachong():
url='http://api.tianapi.com/txapi/ncov/index?key=xxx&date={}'.format(Today)
req = request.Request(url)
resp = request.urlopen(req)
content = resp.read().decode()
data=json.loads(content)
with open('/Users/zhangyuchen/Desktop/latestTrends.json','w') as fp:#將所得的數(shù)據(jù)存儲為json文件
json.dump(data,fp = fp,ensure_ascii = False,indent = 4,sort_keys=True)
#dump函數(shù)有很多參數(shù),第一個是目標(biāo)object,第二個是要寫入的文件對象
print("成功保存為json文件!")
return(re.findall(r'"confirmedCount":(.+?),"',content),re.findall(r'"currentConfirmedCount":(.+?),"',content),re.findall(r'"curedCount":(.+?),"',content))
def connectMysql(cc):
#/usr/local/mysql/bin/mysql -u root -p
db = pymysql.connect("localhost", "root", "密碼", "dbname",charset='utf8' )
cursor = db.cursor()
sql="""insert into {0} (DATE,SICK,SICK_NOW,RECOVER)values('{1}','{2}','{3}','{4}')"""
cursor.execute(sql.format('db1',Today,int(cc[0][0]),int(cc[1][0]),int(cc[2][0])))
cursor.execute(sql.format('db2',Today,int(cc[0][1]),int(cc[1][1]),int(cc[2][1])))
db.commit()
print(("成功將{}數(shù)據(jù)存入數(shù)據(jù)庫!").format(Today))
db.close()
cc=pachong()
connectMysql(cc)
json文件:

2、利用matplotlib庫函數(shù)繪制圖表
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import pymysql
import re
import sys, urllib,json
from urllib import request
#/usr/local/mysql/bin/mysql -u root -p
date=[]
cSick=[]
aSick=[]
cNowSick=[]
aNowSick=[]
cRecover=[]
aRecover=[]
db = pymysql.connect("localhost", "root", "密碼", "trends")
sql="select * from db1 ORDER BY DATE"
cursor = db.cursor()
cursor.execute(sql)
results = cursor.fetchall()
while results:
for row in results:
date.append(row[0].strftime("%d"))
cSick.append(row[1])
cNowSick.append(row[2])
cRecover.append(row[3])
results=cursor.fetchone()
#查詢Abroad Table
sql="select * from db2"
cursor.execute(sql)
results = cursor.fetchall()
while results:
for row in results:
aSick.append(row[1])
aNowSick.append(row[2])
aRecover.append(row[3])
results=cursor.fetchone()
cursor.close()
db.close()
def DrawLineChart(ySick,yNowSick):
plt.plot(x,ySick,color='y',label="Cumulative number of cases",linewidth=3,linestyle="--")
plt.plot(x,yNowSick,color='r',label="Current number of cases",linewidth=3,linestyle="-")
def DrawBarChart(yRecover):
width=0.45#柱子寬度
p2 = plt.bar(x,yRecover,width,label="Cured Count",color="#87CEFA")
Days=len(aSick)
plt.figure(figsize=(16,12), dpi=80)#設(shè)置分辨率為80像素/每英寸
x=np.arange(Days)
#創(chuàng)建兩個子圖
plt.subplot(322)
plt.title("Trends of March")
DrawLineChart(cSick,cNowSick)
DrawBarChart(cRecover)
plt.figlegend()
plt.xticks(x,date)
plt.ylabel('Number')
plt.subplot(324)
#plt.title("Trends of March")
DrawLineChart(aSick,aNowSick)
DrawBarChart(aRecover)
plt.xticks(x,date,rotation=0)
plt.xlabel('Date')
plt.ylabel('Number')
plt.show()
到此這篇關(guān)于利用python繪制數(shù)據(jù)曲線圖的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)python 數(shù)據(jù)曲線圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Python中request發(fā)送post請求傳遞json參數(shù)的問題
這篇文章主要介紹了Python中request發(fā)送post請求傳遞json參數(shù)的問題,在Python中需要傳遞dict參數(shù),利用json.dumps將dict轉(zhuǎn)為json格式用post方法發(fā)起請求,感興趣的朋友跟隨小編一起看看吧2022-08-08
基于python3 pyQt5 QtDesignner實(shí)現(xiàn)窗口化猜數(shù)字游戲功能
這篇文章主要介紹了基于python3 pyQt5 QtDesignner實(shí)現(xiàn)窗口化猜數(shù)字游戲功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
用Python的pandas框架操作Excel文件中的數(shù)據(jù)教程
這篇文章主要介紹了用Python的pandas框架操作Excel文件中的數(shù)據(jù)教程,包括單位格式轉(zhuǎn)換、分類匯總等基本操作,需要的朋友可以參考下2015-03-03
python 遺傳算法求函數(shù)極值的實(shí)現(xiàn)代碼
今天小編就為大家分享一篇python 遺傳算法求函數(shù)極值的實(shí)現(xiàn)代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
Python實(shí)現(xiàn)Windows和Linux之間互相傳輸文件(文件夾)的方法
下面小編就為大家?guī)硪黄狿ython實(shí)現(xiàn)Windows和Linux之間互相傳輸文件(文件夾)的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
Selenium+Python自動化腳本環(huán)境搭建的全過程
說到自動化測試,就不得不提大名鼎鼎的Selenium,Selenium 是如今最常用的自動化測試工具之一,支持快速開發(fā)自動化測試框架,且支持在多種瀏覽器上執(zhí)行測試,下面這篇文章主要給大家介紹了關(guān)于Selenium+Python自動化腳本環(huán)境搭建的相關(guān)資料,需要的朋友可以參考下2021-09-09

