利用python繪制數(shù)據(jù)曲線圖的實(shí)現(xiàn)
”在舉國上下萬眾一心、眾志成城做好新冠肺炎疫情防控工作的特殊時(shí)刻,我們不能親臨主戰(zhàn)場,但我們能堅(jiān)持在大戰(zhàn)中堅(jiān)定信心、不負(fù)韶華?!?/p>
1、爬取新聞保存為json文件,并將繪圖所需數(shù)據(jù)保存至數(shù)據(jù)庫
數(shù)據(jù)庫表結(jié)構(gòu):
代碼部分:
import pymysqlimport reimport sys,urllib,jsonfrom urllib import requestfrom datetime import datetimeimport pandas as pdToday=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ù)存儲(chǔ)為json文件 json.dump(data,fp = fp,ensure_ascii = False,indent = 4,sort_keys=True) #dump函數(shù)有很多參數(shù),第一個(gè)是目標(biāo)object,第二個(gè)是要寫入的文件對象 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 npimport matplotlib.pyplot as pltimport matplotlibimport pymysqlimport reimport sys, urllib,jsonfrom urllib import request#/usr/local/mysql/bin/mysql -u root -pdate=[]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 Tablesql='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)建兩個(gè)子圖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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
