日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 图表_用 Python 让你的数据图表动起来

發(fā)布時間:2023/12/15 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 图表_用 Python 让你的数据图表动起来 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在讀技術(shù)博客的過程中,我們會發(fā)現(xiàn)那些能夠把知識、成果講透的博主很多都會做動態(tài)圖表。他們的圖是怎么做的?難度大嗎?

這篇文章就介紹了 Python 中一種簡單的動態(tài)圖表制作方法。

數(shù)據(jù)暴增的年代,數(shù)據(jù)科學(xué)家、分析師在被要求對數(shù)據(jù)有更深的理解與分析的同時,還需要將結(jié)果有效地傳遞給他人。如何讓目標(biāo)聽眾更直觀地理解?當(dāng)然是將數(shù)據(jù)可視化啊,而且最好是動態(tài)可視化。

本文將以線型圖、條形圖和餅圖為例,系統(tǒng)地講解如何讓你的數(shù)據(jù)圖表動起來。

這些動態(tài)圖表是用什么做的?接觸過數(shù)據(jù)可視化的同學(xué)應(yīng)該對 Python 里的 Matplotlib 庫并不陌生。它是一個基于 Python 的開源數(shù)據(jù)繪圖包,僅需幾行代碼就可以幫助開發(fā)者生成直方圖、功率譜、條形圖、散點圖等。這個庫里有個非常實用的擴展包——FuncAnimation,可以讓我們的靜態(tài)圖表動起來。FuncAnimation 是 Matplotlib 庫中 Animation 類的一部分,后續(xù)會展示多個示例。如果是首次接觸,你可以將這個函數(shù)簡單地理解為一個 While 循環(huán),不停地在 “畫布” 上重新繪制目標(biāo)數(shù)據(jù)圖。如何使用 FuncAnimation?這個過程始于以下兩行代碼:import matplotlib.animation as anianimator = ani.FuncAnimation(fig, chartfunc, interval = 100)從中我們可以看到 FuncAnimation 的幾個輸入:
  • fig 是用來 「繪制圖表」的 figure 對象;

  • chartfunc 是一個以數(shù)字為輸入的函數(shù),其含義為時間序列上的時間;

  • interval 這個更好理解,是幀之間的間隔延遲,以毫秒為單位,默認值為 200。

這是三個關(guān)鍵輸入,當(dāng)然還有更多可選輸入,感興趣的讀者可查看原文檔,這里不再贅述。下一步要做的就是將數(shù)據(jù)圖表參數(shù)化,從而轉(zhuǎn)換為一個函數(shù),然后將該函數(shù)時間序列中的點作為輸入,設(shè)置完成后就可以正式開始了。在開始之前依舊需要確認你是否對基本的數(shù)據(jù)可視化有所了解。也就是說,我們先要將數(shù)據(jù)進行可視化處理,再進行動態(tài)處理。按照以下代碼進行基本調(diào)用。另外,這里將采用大型流行病的傳播數(shù)據(jù)作為案例數(shù)據(jù)(包括每天的死亡人數(shù))。import matplotlib.animation as aniimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdurl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'df = pd.read_csv(url, delimiter=',', header='infer')df_interest = df.loc[df['Country/Region'].isin(['United Kingdom', 'US', 'Italy', 'Germany'])& df['Province/State'].isna]df_interest.rename(index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True)df1 = df_interest.transposedf1 = df1.drop(['Province/State', 'Country/Region', 'Lat', 'Long'])df1 = df1.loc[(df1 != 0).any(1)]df1.index = pd.to_datetime(df1.index)繪制三種常見動態(tài)圖表1、繪制動態(tài)線型圖

如下所示,首先需要做的第一件事是定義圖的各項,這些基礎(chǔ)項設(shè)定之后就會保持不變。它們包括:創(chuàng)建 figure 對象,x 標(biāo)和 y 標(biāo),設(shè)置線條顏色和 figure 邊距等:import numpy as npimport matplotlib.pyplot as pltcolor = ['red', 'green', 'blue', 'orange']fig = plt.figureplt.xticks(rotation=45, ha="right", rotation_mode="anchor") #rotate the x-axis valuesplt.subplots_adjust(bottom = 0.2, top = 0.9) #ensuring the dates (on the x-axis) fit in the screenplt.ylabel('No of Deaths')plt.xlabel('Dates')接下來設(shè)置 curve 函數(shù),進而使用 .FuncAnimation 讓它動起來:defbuildmebarchart(i=int):plt.legend(df1.columns)p = plt.plot(df1[:i].index, df1[:i].values) #note it only returns the dataset, up to the point ifor i in range(0,4):p[i].set_color(color[i]) #set the colour of each curveimport matplotlib.animation as anianimator = ani.FuncAnimation(fig, buildmebarchart, interval = 100)plt.show2、動態(tài)餅狀圖

可以觀察到,其代碼結(jié)構(gòu)看起來與線型圖并無太大差異,但依舊有細小的差別。import numpy as npimport matplotlib.pyplot as pltfig,ax = plt.subplotsexplode=[0.01,0.01,0.01,0.01] #pop out each slice from the piedef getmepie(i):defabsolute_value(val): #turn % back to a numbera = np.round(val/100.*df1.head(i).max.sum, 0)return int(a)ax.clearplot = df1.head(i).max.plot.pie(y=df1.columns,autopct=absolute_value, label='',explode = explode, shadow = True)plot.set_title('Total Number of Deaths\n' + str(df1.index[min( i, len(df1.index)-1 )].strftime('%y-%m-%d')), fontsize=12)import matplotlib.animation as anianimator = ani.FuncAnimation(fig, getmepie, interval = 200)plt.show主要區(qū)別在于,動態(tài)餅狀圖的代碼每次循環(huán)都會返回一組數(shù)值,但在線型圖中返回的是我們所在點之前的整個時間序列。返回時間序列通過 df1.head(i) 來實現(xiàn),而. max則保證了我們僅獲得最新的數(shù)據(jù),因為流行病導(dǎo)致死亡的總數(shù)只有兩種變化:維持現(xiàn)有數(shù)量或持續(xù)上升。df1.head(i).max3、動態(tài)條形圖創(chuàng)建動態(tài)條形圖的難度與上述兩個案例并無太大差別。在這個案例中,作者定義了水平和垂直兩種條形圖,讀者可以根據(jù)自己的實際需求來選擇圖表類型并定義變量欄。fig = plt.figurebar = ''def buildmebarchart(i=int):iv = min(i, len(df1.index)-1) #the loop iterates an extra one time, which causes the dataframes to go out of bounds. This was the easiest (most lazy) way to solve this :)objects = df1.max.indexy_pos = np.arange(len(objects))performance = df1.iloc[[iv]].values.tolist[0]if bar == 'vertical':plt.bar(y_pos, performance, align='center', color=['red', 'green', 'blue', 'orange'])plt.xticks(y_pos, objects)plt.ylabel('Deaths')plt.xlabel('Countries')plt.title('Deaths per Country \n' + str(df1.index[iv].strftime('%y-%m-%d')))else:plt.barh(y_pos, performance, align='center', color=['red', 'green', 'blue', 'orange'])plt.yticks(y_pos, objects)plt.xlabel('Deaths')plt.ylabel('Countries')animator = ani.FuncAnimation(fig, buildmebarchart, interval=100)plt.show在制作完成后,存儲這些動態(tài)圖就非常簡單了,可直接使用以下代碼:animator.save(r'C:\temp\myfirstAnimation.gif')感興趣的讀者如想獲得詳細信息可參考:https://matplotlib.org/3.1.1/api/animation_api.html。

- END -

原文鏈接:

Costas Andreou

https://towardsdatascience.com/learn-how-to-create-animated-graphs-in-python-fce780421afe

文源網(wǎng)絡(luò),僅供學(xué)習(xí)之用。如有侵權(quán),聯(lián)系刪除。

往期精彩

◆ ?50款開源工具你都用過嗎?

◆ ?python+C、C++混合編程的應(yīng)用

◆ ?python網(wǎng)絡(luò)爬蟲的基本原理詳解

◆ ?Python自動操控excel,一小時解決你一天的工作

◆ ?如何用Python增強Excel,減少處理復(fù)雜數(shù)據(jù)的痛苦?

總結(jié)

以上是生活随笔為你收集整理的python 图表_用 Python 让你的数据图表动起来的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。