兩個簡單的代碼片段讓你的圖表動起來
本篇文章整列了2個簡單的代碼片段,可以讓你的圖表動起來。
動畫
Python中有許多用于繪制圖形的庫。Matplotlib, Seaborn, Bokeh, Plotly等等。
但是我們繪圖的目的是要向聽眾和要傳遞的信息。如果你的圖能夠動起來那么他們肯定會讓聽眾在看第一眼的時候就印象深刻。但是并不是每個圖形或數據集都適合動畫。一般情況下,動畫對時間序列來說非常有效。例如,根據時間變化進行數據的對比。
Plotly Express
Plotly Express,可以直接為我們創建動態圖表:
import plotly.express as px
import pandas as pd
import numpy as np
讓我們在數據集中創建一些值。
df = pd.DataFrame( {'week': np.random.randint(1,21, size=200),
'P1': np.random.randint(10,220, size=200),
'P2': np.random.randint(15,200, size=200),
'P3': np.random.randint(10,490, size=200),
'P4': np.random.randint(10,980, size=200) } )
df = pd.DataFrame( {'week': np.random.randint(1,21, size=200),
'P1': np.random.randint(10,220, size=200),
'P2': np.random.randint(15,200, size=200),
'P3': np.random.randint(10,490, size=200),
'P4': np.random.randint(10,980, size=200) } )
現在我們可以繪制一個動畫圖來查看產品按周的變化情況。
創建散點圖動畫也同樣簡單。
fig = px.scatter(df, x="week", y="sales", animation_frame="week", animation_group="product", size="sales", color="product", hover_name="product", range_x=[0,20], range_y=[0,800])
fig.update_layout(height=600, width=1000)
gif庫
如果你向我一樣是matplot和seaborn的粉絲,并且不太喜歡用Plotly的話,那么可以試試這個庫。這個庫的作用是創建一系列繪圖,并將它們放在一個幀序列中并創建一個動態的gif圖。
首先,還是獲取一些用于繪圖的時間序列數據。
import seaborn as sns
df = sns.load_dataset('flights')
接下來創建一個函數,該函數將為每個觀察創建一個繪圖。
@gif.frame
def plot_flights(df, i):
df = df.copy()
# Get the year for the plot title
yr = df['year'][i]
# Force X axis to be entirely plotted at once
df.iloc[i:] = np.nan
#Plot
ax = df.plot(x='month', y= 'passengers', legend=False,
style="o-", figsize=(20,10))
ax.set_title(f"Air Passengers {yr}", size=20)
ax.set_xlabel("Months")
ax.set_ylabel("Number of Passengers")
@gif.frame是GIF庫用來創建幀序列的裝飾器。
df.iloc[i:] = np.nan將把所有未來的數據轉換到NA。這是一種每次只繪制一個值的編程方式(i=0所有都為nan, i=1,只繪制索引0,i=2,只繪制0和1…),通過這種方法我們可以端到端繪制X軸,因為在動畫期間是不會改變的。這樣也可以保持圖表的大小不變,使其更容易觀看。
現在我們使用函數創建一個循環來創建幀。
frames = []
for i in range(df.shape[0]):
frame = plot_flights(df, i)
frames.append(frame)
最后,保存生成的GIF圖像。
gif.save(frames, 'gif_example.gif', duration=180)
看,是不是很簡單
最后總結
動畫圖是一個很有影響力的展示方法,但是并不是所有的圖都適合動畫化。我們應該根據實際的情況來選擇是否需要創建動畫圖,因為動畫圖并不是深入分析的最佳選擇他只是在視覺上有一些更大的沖擊,所以當你需要觀察、比較和理解時也許靜態圖是更好的選擇。
要創建動圖,我建議您使用gif庫,因為對于這種圖形類型,它比plotly更簡單(因為我個人更喜歡seaborn,哈)。