天天看點

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

昨天行哥給大家統計了資料可視化前30張圖表代碼和案例給大家,今天把分享Python可視化案例TOP 50下,如果想轉行做資料分析,這兩篇推文強烈建議收藏,對于學習有任何問題都可以點選閱讀原文向行哥提問哦

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

5.組成

5.1華夫餅圖

5.2 餅圖

5.3 樹狀圖

5.4 條形圖

6 時間序列

6.1時間序列圖

6.2 帶有标記的時間序列圖

6.3自相關(ACF)和部分自相關(PACF)圖

6.4 交叉相關圖

6.5 時間序列分解圖

6.6 多時間序列圖

6.7 雙y軸圖

6.8 具有誤差帶的時間序列

6.9 堆積面積圖

6.10 區域圖(未堆疊)

6.11 月曆熱圖

6.12 季節性圖

7 分組

7.1 樹狀圖

7.2 聚類圖

7.3 安德魯斯曲線

7.4 平行坐标圖

5.組成

5.1華夫餅圖

waffle可以使用該pywaffle軟體包建立該圖表,并用于顯示較大人群中各組的組成。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

#! pip install pywaffle

# Reference: https://stackoverflow.com/questions/41400136/how-to-do-waffle-charts-in-python-square-piechart

from pywaffle import Waffle

# Import

df_raw = pd.read_csv("data/mpg_ggplot2.csv")

# Prepare Data

df = df_raw.groupby('class').size().reset_index(name='counts')

n_categories = df.shape[0]

colors = [plt.cm.inferno_r(i/float(n_categories)) for i in range(n_categories)]

# Draw Plot and Decorate

fig = plt.figure(

FigureClass=Waffle,

plots={

'111': {

'values': df['counts'],

'labels': ["{0} ({1})".format(n[0], n[1]) for n in df[['class', 'counts']].itertuples()],

'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12},

'title': {'label': '# Vehicles by Class', 'loc': 'center', 'fontsize':18}

},

},

rows=7,

colors=colors,

figsize=(16, 9)

)

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

#! pip install pywaffle

from pywaffle import Waffle

# Import

# df_raw = pd.read_csv("data/mpg_ggplot2.csv")

# Prepare Data

# By Class Data

df_class = df_raw.groupby('class').size().reset_index(name='counts_class')

n_categories = df_class.shape[0]

colors_class = [plt.cm.Set3(i/float(n_categories)) for i in range(n_categories)]

# By Cylinders Data

df_cyl = df_raw.groupby('cyl').size().reset_index(name='counts_cyl')

n_categories = df_cyl.shape[0]

colors_cyl = [plt.cm.Spectral(i/float(n_categories)) for i in range(n_categories)]

# By Make Data

df_make = df_raw.groupby('manufacturer').size().reset_index(name='counts_make')

n_categories = df_make.shape[0]

colors_make = [plt.cm.tab20b(i/float(n_categories)) for i in range(n_categories)]

# Draw Plot and Decorate

fig = plt.figure(

FigureClass=Waffle,

plots={

'311': {

'values': df_class['counts_class'],

'labels': ["{1}".format(n[0], n[1]) for n in df_class[['class', 'counts_class']].itertuples()],

'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Class'},

'title': {'label': '# Vehicles by Class', 'loc': 'center', 'fontsize':18},

'colors': colors_class

},

'312': {

'values': df_cyl['counts_cyl'],

'labels': ["{1}".format(n[0], n[1]) for n in df_cyl[['cyl', 'counts_cyl']].itertuples()],

'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Cyl'},

'title': {'label': '# Vehicles by Cyl', 'loc': 'center', 'fontsize':18},

'colors': colors_cyl

},

'313': {

'values': df_make['counts_make'],

'labels': ["{1}".format(n[0], n[1]) for n in df_make[['manufacturer', 'counts_make']].itertuples()],

'legend': {'loc': 'upper left', 'bbox_to_anchor': (1.05, 1), 'fontsize': 12, 'title':'Manufacturer'},

'title': {'label': '# Vehicles by Make', 'loc': 'center', 'fontsize':18},

'colors': colors_make

}

},

rows=9,

figsize=(16, 14)

)

5.2 餅圖

餅圖是顯示組組成的經典方法。但是,如今一般不建議使用它,因為餡餅部分的面積有時可能會引起誤解。是以,如果要使用餅圖,強烈建議明确寫下餅圖各部分的百分比或數字。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import

df_raw = pd.read_csv("data/mpg_ggplot2.csv")

# Prepare Data

df = df_raw.groupby('class').size()

# Make the plot with pandas

df.plot(kind='pie', subplots=True, figsize=(8, 8), dpi= 80)

plt.title("Pie Chart of Vehicle Class - Bad")

plt.ylabel("")

plt.show()

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import

df_raw = pd.read_csv("data/mpg_ggplot2.csv")

# Prepare Data

df = df_raw.groupby('class').size().reset_index(name='counts')

# Draw Plot

fig, ax = plt.subplots(figsize=(12, 7), subplot_kw=dict(aspect="equal"), dpi= 80)

data = df['counts']

categories = df['class']

explode = [0,0,0,0,0,0.1,0]

def func(pct, allvals):

absolute = int(pct/100.*np.sum(allvals))

return "{:.1f}% ({:d} )".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data,

autopct=lambda pct: func(pct, data),

textprops=dict(color="w"),

colors=plt.cm.Dark2.colors,

startangle=140,

explode=explode)

# Decoration

ax.legend(wedges, categories, title="Vehicle Class", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight=700)

ax.set_title("Class of Vehicles: Pie Chart")

plt.show()

5.3 樹狀圖

樹形圖類似于餅形圖,并且可以更好地完成工作,而不會誤導每個組的貢獻。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# pip install squarify

import squarify

# Import Data

df_raw = pd.read_csv("data/mpg_ggplot2.csv")

# Prepare Data

df = df_raw.groupby('class').size().reset_index(name='counts')

labels = df.apply(lambda x: str(x[0]) + "\n (" + str(x[1]) + ")", axis=1)

sizes = df['counts'].values.tolist()

colors = [plt.cm.Spectral(i/float(len(labels))) for i in range(len(labels))]

# Draw Plot

plt.figure(figsize=(12,8), dpi= 80)

squarify.plot(sizes=sizes, label=labels, color=colors, alpha=.8)

# Decorate

plt.title('Treemap of Vechile Class')

plt.axis('off')

plt.show()

5.4 條形圖

條形圖是一種基于計數或任何給定名額可視化項目的經典方法。在下面的圖表中,我為每個項目使用了不同的顔色,但是您通常可能希望為所有項目選擇一種顔色,除非您按組對它們進行着色。顔色名稱存儲在all_colors下面的代碼中。您可以通過在中設定color參數來更改條形的顔色。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

import random

# Import Data

df_raw = pd.read_csv("data/mpg_ggplot2.csv")

# Prepare Data

df = df_raw.groupby('manufacturer').size().reset_index(name='counts')

n = df['manufacturer'].unique().__len__()+1

all_colors = list(plt.cm.colors.cnames.keys())

random.seed(100)

c = random.choices(all_colors, k=n)

# Plot Bars

plt.figure(figsize=(16,10), dpi= 80)

plt.bar(df['manufacturer'], df['counts'], color=c, width=.5)

for i, val in enumerate(df['counts'].values):

plt.text(i, val, float(val), horizontalalignment='center', verticalalignment='bottom', fontdict={'fontweight':500, 'size':12})

# Decoration

plt.gca().set_xticklabels(df['manufacturer'], rotation=60, horizontalalignment= 'right')

plt.title("Number of Vehicles by Manaufacturers", fontsize=22)

plt.ylabel('# Vehicles')

plt.ylim(0, 45)

plt.show()

6 時間序列

6.1時間序列圖

時間序列圖用于可視化給定名額如何随時間變化。在這裡,您可以了解1949年至1969年之間的航空客運流量如何變化。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import Data

df = pd.read_csv('https://github.com/selva86/datasets/raw/master/AirPassengers.csv')

# Draw Plot

plt.figure(figsize=(16,10), dpi= 80)

plt.plot('date', 'traffic', data=df, color='tab:red')

# Decoration

plt.ylim(50, 750)

xtick_location = df.index.tolist()[::12]

xtick_labels = [x[-4:] for x in df.date.tolist()[::12]]

plt.xticks(ticks=xtick_location, labels=xtick_labels, rotation=0, fontsize=12, horizontalalignment='center', alpha=.7)

plt.yticks(fontsize=12, alpha=.7)

plt.title("Air Passengers Traffic (1949 - 1969)", fontsize=22)

plt.grid(axis='both', alpha=.3)

# Remove borders

plt.gca().spines["top"].set_alpha(0.0)

plt.gca().spines["bottom"].set_alpha(0.3)

plt.gca().spines["right"].set_alpha(0.0)

plt.gca().spines["left"].set_alpha(0.3)

plt.show()

6.2 帶有标記的時間序列圖

下面的時間序列繪制了所有的波峰和波谷,并注釋了標明特殊事件的發生。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import Data

df = pd.read_csv('https://github.com/selva86/datasets/raw/master/AirPassengers.csv')

# Get the Peaks and Troughs

data = df['traffic'].values

doublediff = np.diff(np.sign(np.diff(data)))

peak_locations = np.where(doublediff == -2)[0] + 1

doublediff2 = np.diff(np.sign(np.diff(-1*data)))

trough_locations = np.where(doublediff2 == -2)[0] + 1

# Draw Plot

plt.figure(figsize=(16,10), dpi= 80)

plt.plot('date', 'traffic', data=df, color='tab:blue', label='Air Traffic')

plt.scatter(df.date[peak_locations], df.traffic[peak_locations], marker=mpl.markers.CARETUPBASE, color='tab:green', s=100, label='Peaks')

plt.scatter(df.date[trough_locations], df.traffic[trough_locations], marker=mpl.markers.CARETDOWNBASE, color='tab:red', s=100, label='Troughs')

# Annotate

for t, p in zip(trough_locations[1::5], peak_locations[::3]):

plt.text(df.date[p], df.traffic[p]+15, df.date[p], horizontalalignment='center', color='darkgreen')

plt.text(df.date[t], df.traffic[t]-35, df.date[t], horizontalalignment='center', color='darkred')

# Decoration

plt.ylim(50,750)

xtick_location = df.index.tolist()[::6]

xtick_labels = df.date.tolist()[::6]

plt.xticks(ticks=xtick_location, labels=xtick_labels, rotation=90, fontsize=12, alpha=.7)

plt.title("Peak and Troughs of Air Passengers Traffic (1949 - 1969)", fontsize=22)

plt.yticks(fontsize=12, alpha=.7)

# Lighten borders

plt.gca().spines["top"].set_alpha(.0)

plt.gca().spines["bottom"].set_alpha(.3)

plt.gca().spines["right"].set_alpha(.0)

plt.gca().spines["left"].set_alpha(.3)

plt.legend(loc='upper left')

plt.grid(axis='y', alpha=.3)

plt.show()

6.3自相關(ACF)和部分自相關(PACF)圖

ACF圖顯示了時間序列與其自身滞後的相關性。每條垂直線(在自相關圖上)代表序列與從滞後0開始的滞後之間的相關性。圖中的藍色陰影區域是顯着性水準。藍線以上的那些滞後就是巨大的滞後。

那麼如何解釋呢?

對于AirPassengers,我們看到多達14個滞後已越過藍線,是以意義重大。這意味着,距今已有14年之久的航空客運量對今天的客運量産生了影響。

另一方面,PACF顯示了任何給定的(時間序列)滞後與目前序列之間的自相關,但是去除了兩者之間的滞後。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# Import Data

df = pd.read_csv('https://github.com/selva86/datasets/raw/master/AirPassengers.csv')

# Draw Plot

fig, (ax1, ax2) = plt.subplots(1, 2,figsize=(16,6), dpi= 80)

plot_acf(df.traffic.tolist(), ax=ax1, lags=50)

plot_pacf(df.traffic.tolist(), ax=ax2, lags=20)

# Decorate

# lighten the borders

ax1.spines["top"].set_alpha(.3); ax2.spines["top"].set_alpha(.3)

ax1.spines["bottom"].set_alpha(.3); ax2.spines["bottom"].set_alpha(.3)

ax1.spines["right"].set_alpha(.3); ax2.spines["right"].set_alpha(.3)

ax1.spines["left"].set_alpha(.3); ax2.spines["left"].set_alpha(.3)

# font size of tick labels

ax1.tick_params(axis='both', labelsize=12)

ax2.tick_params(axis='both', labelsize=12)

plt.show()

6.4 交叉相關圖

互相關圖顯示了兩個時間序列之間的時滞。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

import statsmodels.tsa.stattools as stattools

# Import Data

df = pd.read_csv('https://github.com/selva86/datasets/raw/master/mortality.csv')

x = df['mdeaths']

y = df['fdeaths']

# Compute Cross Correlations

ccs = stattools.ccf(x, y)[:100]

nlags = len(ccs)

# Compute the Significance level

# ref: https://stats.stackexchange.com/questions/3115/cross-correlation-significance-in-r/3128#3128

conf_level = 2 / np.sqrt(nlags)

# Draw Plot

plt.figure(figsize=(12,7), dpi= 80)

plt.hlines(0, xmin=0, xmax=100, color='gray')  # 0 axis

plt.hlines(conf_level, xmin=0, xmax=100, color='gray')

plt.hlines(-conf_level, xmin=0, xmax=100, color='gray')

plt.bar(x=np.arange(len(ccs)), height=ccs, width=.3)

# Decoration

plt.title('$Cross\; Correlation\; Plot:\; mdeaths\; vs\; fdeaths$', fontsize=22)

plt.xlim(0,len(ccs))

plt.show()

6.5 時間序列分解圖

時間序列分解圖顯示了時間序列按趨勢,季節和殘差成分的分解。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

from statsmodels.tsa.seasonal import seasonal_decompose

from dateutil.parser import parse

# Import Data

df = pd.read_csv('https://github.com/selva86/datasets/raw/master/AirPassengers.csv')

dates = pd.DatetimeIndex([parse(d).strftime('%Y-%m-01') for d in df['date']])

df.set_index(dates, inplace=True)

# Decompose

result = seasonal_decompose(df['traffic'], model='multiplicative')

# Plot

plt.rcParams.update({'figure.figsize': (10,10)})

result.plot().suptitle('Time Series Decomposition of Air Passengers')

plt.show()

6.6 多時間序列圖

您可以在同一張圖表上繪制測量同一值的多個時間序列,如下所示。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import Data

df = pd.read_csv('https://github.com/selva86/datasets/raw/master/mortality.csv')

# Define the upper limit, lower limit, interval of Y axis and colors

y_LL = 100

y_UL = int(df.iloc[:, 1:].max().max()*1.1)

y_interval = 400

mycolors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange']

# Draw Plot and Annotate

fig, ax = plt.subplots(1,1,figsize=(16, 9), dpi= 80)

columns = df.columns[1:]

for i, column in enumerate(columns):

plt.plot(df.date.values, df[column].values, lw=1.5, color=mycolors[i])

plt.text(df.shape[0]+1, df[column].values[-1], column, fontsize=14, color=mycolors[i])

# Draw Tick lines

for y in range(y_LL, y_UL, y_interval):

plt.hlines(y, xmin=0, xmax=71, colors='black', alpha=0.3, linestyles="--", lw=0.5)

# Decorations

plt.tick_params(axis="both", which="both", bottom=False, top=False,

labelbottom=True, left=False, right=False, labelleft=True)

# Lighten borders

plt.gca().spines["top"].set_alpha(.3)

plt.gca().spines["bottom"].set_alpha(.3)

plt.gca().spines["right"].set_alpha(.3)

plt.gca().spines["left"].set_alpha(.3)

plt.title('Number of Deaths from Lung Diseases in the UK (1974-1979)', fontsize=22)

plt.yticks(range(y_LL, y_UL, y_interval), [str(y) for y in range(y_LL, y_UL, y_interval)], fontsize=12)

plt.xticks(range(0, df.shape[0], 12), df.date.values[::12], horizontalalignment='left', fontsize=12)

plt.ylim(y_LL, y_UL)

plt.xlim(-2, 80)

plt.show()

6.7 雙y軸圖

如果要顯示在同一時間點測量兩個不同量的兩個時間序列,則可以在右邊的第二個Y軸上再次繪制第二個序列。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")

x = df['date']

y1 = df['psavert']

y2 = df['unemploy']

# Plot Line1 (Left Y Axis)

fig, ax1 = plt.subplots(1,1,figsize=(16,9), dpi= 80)

ax1.plot(x, y1, color='tab:red')

# Plot Line2 (Right Y Axis)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

ax2.plot(x, y2, color='tab:blue')

# Decorations

# ax1 (left Y axis)

ax1.set_xlabel('Year', fontsize=20)

ax1.tick_params(axis='x', rotation=0, labelsize=12)

ax1.set_ylabel('Personal Savings Rate', color='tab:red', fontsize=20)

ax1.tick_params(axis='y', rotation=0, labelcolor='tab:red' )

ax1.grid(alpha=.4)

# ax2 (right Y axis)

ax2.set_ylabel("# Unemployed (1000's)", color='tab:blue', fontsize=20)

ax2.tick_params(axis='y', labelcolor='tab:blue')

ax2.set_xticks(np.arange(0, len(x), 60))

ax2.set_xticklabels(x[::60], rotation=90, fontdict={'fontsize':10})

ax2.set_title("Personal Savings Rate vs Unemployed: Plotting in Secondary Y Axis", fontsize=22)

fig.tight_layout()

plt.show()

6.8 具有誤差帶的時間序列

如果您具有每個時間點(日期/時間戳)具有多個觀測值的時間序列資料集,則可以建構帶有誤差帶的時間序列。您可以在下面看到一些基于一天中不同時間下達的訂單的示例。另一個例子是在45天的時間内到達的訂單數量。

在這種方法中,訂單數量的平均值由白線表示。然後計算出95%的置信帶并圍繞均值繪制。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

from scipy.stats import sem

# Import Data

df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/user_orders_hourofday.csv")

df_mean = df.groupby('order_hour_of_day').quantity.mean()

df_se = df.groupby('order_hour_of_day').quantity.apply(sem).mul(1.96)

# Plot

plt.figure(figsize=(16,10), dpi= 80)

plt.ylabel("# Orders", fontsize=16)

x = df_mean.index

plt.plot(x, df_mean, color="white", lw=2)

plt.fill_between(x, df_mean - df_se, df_mean + df_se, color="#3F5D7D")

# Decorations

# Lighten borders

plt.gca().spines["top"].set_alpha(0)

plt.gca().spines["bottom"].set_alpha(1)

plt.gca().spines["right"].set_alpha(0)

plt.gca().spines["left"].set_alpha(1)

plt.xticks(x[::2], [str(d) for d in x[::2]] , fontsize=12)

plt.title("User Orders by Hour of Day (95% confidence)", fontsize=22)

plt.xlabel("Hour of Day")

s, e = plt.gca().get_xlim()

plt.xlim(s, e)

# Draw Horizontal Tick lines

for y in range(8, 20, 2):

plt.hlines(y, xmin=s, xmax=e, colors='black', alpha=0.5, linestyles="--", lw=0.5)

plt.show()

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

"Data Source: https://www.kaggle.com/olistbr/brazilian-ecommerce#olist_orders_dataset.csv"

from dateutil.parser import parse

from scipy.stats import sem

# Import Data

df_raw = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/orders_45d.csv',

parse_dates=['purchase_time', 'purchase_date'])

# Prepare Data: Daily Mean and SE Bands

df_mean = df_raw.groupby('purchase_date').quantity.mean()

df_se = df_raw.groupby('purchase_date').quantity.apply(sem).mul(1.96)

# Plot

plt.figure(figsize=(16,10), dpi= 80)

plt.ylabel("# Daily Orders", fontsize=16)

x = [d.date().strftime('%Y-%m-%d') for d in df_mean.index]

plt.plot(x, df_mean, color="white", lw=2)

plt.fill_between(x, df_mean - df_se, df_mean + df_se, color="#3F5D7D")

# Decorations

# Lighten borders

plt.gca().spines["top"].set_alpha(0)

plt.gca().spines["bottom"].set_alpha(1)

plt.gca().spines["right"].set_alpha(0)

plt.gca().spines["left"].set_alpha(1)

plt.xticks(x[::6], [str(d) for d in x[::6]] , fontsize=12)

plt.title("Daily Order Quantity of Brazilian Retail with Error Bands (95% confidence)", fontsize=20)

# Axis limits

s, e = plt.gca().get_xlim()

plt.xlim(s, e-2)

plt.ylim(4, 10)

# Draw Horizontal Tick lines

for y in range(5, 10, 1):

plt.hlines(y, xmin=s, xmax=e, colors='black', alpha=0.5, linestyles="--", lw=0.5)

plt.show()

6.9 堆積面積圖

堆積面積圖直覺地顯示了多個時間序列的貢獻程度,是以可以輕松地進行互相比較。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import Data

df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/nightvisitors.csv')

# Decide Colors

mycolors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:brown', 'tab:grey', 'tab:pink', 'tab:olive']

# Draw Plot and Annotate

fig, ax = plt.subplots(1,1,figsize=(16, 9), dpi= 80)

columns = df.columns[1:]

labs = columns.values.tolist()

# Prepare data

x  = df['yearmon'].values.tolist()

y0 = df[columns[0]].values.tolist()

y1 = df[columns[1]].values.tolist()

y2 = df[columns[2]].values.tolist()

y3 = df[columns[3]].values.tolist()

y4 = df[columns[4]].values.tolist()

y5 = df[columns[5]].values.tolist()

y6 = df[columns[6]].values.tolist()

y7 = df[columns[7]].values.tolist()

y = np.vstack([y0, y2, y4, y6, y7, y5, y1, y3])

# Plot for each column

labs = columns.values.tolist()

ax = plt.gca()

ax.stackplot(x, y, labels=labs, colors=mycolors, alpha=0.8)

# Decorations

ax.set_title('Night Visitors in Australian Regions', fontsize=18)

ax.set(ylim=[0, 100000])

ax.legend(fontsize=10, ncol=4)

plt.xticks(x[::5], fontsize=10, horizontalalignment='center')

plt.yticks(np.arange(10000, 100000, 20000), fontsize=10)

plt.xlim(x[0], x[-1])

# Lighten borders

plt.gca().spines["top"].set_alpha(0)

plt.gca().spines["bottom"].set_alpha(.3)

plt.gca().spines["right"].set_alpha(0)

plt.gca().spines["left"].set_alpha(.3)

plt.show()

6.10 區域圖(未堆疊)

未堆積的面積圖用于可視化兩個或多個系列相對于彼此的進度(漲跌)。在下面的圖表中,您可以清楚地看到随着失業時間的中位數增加,個人儲蓄率如何下降。未堆積面積圖很好地顯示了這種現象。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

# Import Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")

# Prepare Data

x = df['date'].values.tolist()

y1 = df['psavert'].values.tolist()

y2 = df['uempmed'].values.tolist()

mycolors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:brown', 'tab:grey', 'tab:pink', 'tab:olive']

columns = ['psavert', 'uempmed']

# Draw Plot

fig, ax = plt.subplots(1, 1, figsize=(16,9), dpi= 80)

ax.fill_between(x, y1=y1, y2=0, label=columns[1], alpha=0.5, color=mycolors[1], linewidth=2)

ax.fill_between(x, y1=y2, y2=0, label=columns[0], alpha=0.5, color=mycolors[0], linewidth=2)

# Decorations

ax.set_title('Personal Savings Rate vs Median Duration of Unemployment', fontsize=18)

ax.set(ylim=[0, 30])

ax.legend(loc='best', fontsize=12)

plt.xticks(x[::50], fontsize=10, horizontalalignment='center')

plt.yticks(np.arange(2.5, 30.0, 2.5), fontsize=10)

plt.xlim(-10, x[-1])

# Draw Tick lines

for y in np.arange(2.5, 30.0, 2.5):

plt.hlines(y, xmin=0, xmax=len(x), colors='black', alpha=0.3, linestyles="--", lw=0.5)

# Lighten borders

plt.gca().spines["top"].set_alpha(0)

plt.gca().spines["bottom"].set_alpha(.3)

plt.gca().spines["right"].set_alpha(0)

plt.gca().spines["left"].set_alpha(.3)

plt.show()

6.11 月曆熱圖

月曆地圖是與時間序列相比可視化基于時間的資料的替代方法,而不是首選方法。盡管可以在視覺上吸引人,但數值并不十分明顯。但是,它可以有效地很好地描繪出極端值和假日效果。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

import matplotlib as mpl

import calmap

# Import Data

df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/yahoo.csv", parse_dates=['date'])

df.set_index('date', inplace=True)

# Plot

plt.figure(figsize=(16,10), dpi= 80)

calmap.calendarplot(df['2014']['VIX.Close'], fig_kws={'figsize': (16,10)}, yearlabel_kws={'color':'black', 'fontsize':14}, subplot_kws={'title':'Yahoo Stock Prices'})

plt.show()

6.12 季節性圖

季節性圖可用于比較上一個季節的同一天(年/月/周等)的時間序列執行情況。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

from dateutil.parser import parse

# Import Data

df = pd.read_csv('https://github.com/selva86/datasets/raw/master/AirPassengers.csv')

# Prepare data

df['year'] = [parse(d).year for d in df.date]

df['month'] = [parse(d).strftime('%b') for d in df.date]

years = df['year'].unique()

# Draw Plot

mycolors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange', 'tab:brown', 'tab:grey', 'tab:pink', 'tab:olive', 'deeppink', 'steelblue', 'firebrick', 'mediumseagreen']

plt.figure(figsize=(16,10), dpi= 80)

for i, y in enumerate(years):

plt.plot('month', 'traffic', data=df.loc[df.year==y, :], color=mycolors[i], label=y)

plt.text(df.loc[df.year==y, :].shape[0]-.9, df.loc[df.year==y, 'traffic'][-1:].values[0], y, fontsize=12, color=mycolors[i])

# Decoration

plt.ylim(50,750)

plt.xlim(-0.3, 11)

plt.ylabel('$Air Traffic$')

plt.yticks(fontsize=12, alpha=.7)

plt.title("Monthly Seasonal Plot: Air Passengers Traffic (1949 - 1969)", fontsize=22)

plt.grid(axis='y', alpha=.3)

# Remove borders

plt.gca().spines["top"].set_alpha(0.0)

plt.gca().spines["bottom"].set_alpha(0.5)

plt.gca().spines["right"].set_alpha(0.0)

plt.gca().spines["left"].set_alpha(0.5)

# plt.legend(loc='upper right', ncol=2, fontsize=12)

plt.show()

7 分組

7.1 樹狀圖

樹狀圖根據給定的距離度量将相似的點組合在一起,并根據該點的相似性将它們組織成樹狀連結。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

import scipy.cluster.hierarchy as shc

# Import Data

df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/USArrests.csv')

# Plot

plt.figure(figsize=(16, 10), dpi= 80)

plt.title("USArrests Dendograms", fontsize=22)

dend = shc.dendrogram(shc.linkage(df[['Murder', 'Assault', 'UrbanPop', 'Rape']], method='ward'), labels=df.State.values, color_threshold=100)

plt.xticks(fontsize=12)

plt.show()

7.2 聚類圖

群集圖可用于劃分屬于同一群集的點。下面是一個示例性示例,根據USArrests資料集将美國各州分為5個組。該聚類圖使用“謀殺”和“攻擊”列作為X軸和Y軸。或者,您可以使用第一個至第一個主要成分作為X和Y軸。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

from sklearn.cluster import AgglomerativeClustering

from scipy.spatial import ConvexHull

# Import Data

df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/USArrests.csv')

# Agglomerative Clustering

cluster = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')

cluster.fit_predict(df[['Murder', 'Assault', 'UrbanPop', 'Rape']])

# Plot

plt.figure(figsize=(14, 10), dpi= 80)

plt.scatter(df.iloc[:,0], df.iloc[:,1], c=cluster.labels_, cmap='tab10')

# Encircle

def encircle(x,y, ax=None, **kw):

if not ax: ax=plt.gca()

p = np.c_[x,y]

hull = ConvexHull(p)

poly = plt.Polygon(p[hull.vertices,:], **kw)

ax.add_patch(poly)

# Draw polygon surrounding vertices

encircle(df.loc[cluster.labels_ == 0, 'Murder'], df.loc[cluster.labels_ == 0, 'Assault'], ec="k", fc="gold", alpha=0.2, linewidth=0)

encircle(df.loc[cluster.labels_ == 1, 'Murder'], df.loc[cluster.labels_ == 1, 'Assault'], ec="k", fc="tab:blue", alpha=0.2, linewidth=0)

encircle(df.loc[cluster.labels_ == 2, 'Murder'], df.loc[cluster.labels_ == 2, 'Assault'], ec="k", fc="tab:red", alpha=0.2, linewidth=0)

encircle(df.loc[cluster.labels_ == 3, 'Murder'], df.loc[cluster.labels_ == 3, 'Assault'], ec="k", fc="tab:green", alpha=0.2, linewidth=0)

encircle(df.loc[cluster.labels_ == 4, 'Murder'], df.loc[cluster.labels_ == 4, 'Assault'], ec="k", fc="tab:orange", alpha=0.2, linewidth=0)

# Decorations

plt.xlabel('Murder'); plt.xticks(fontsize=12)

plt.ylabel('Assault'); plt.yticks(fontsize=12)

plt.title('Agglomerative Clustering of USArrests (5 Groups)', fontsize=22)

plt.show()

7.3 安德魯斯曲線

安德魯斯曲線可幫助可視化是否存在基于給定分組的數字特征的固有分組。如果要素(資料集中的列)不能幫助區分組(,則行将無法很好地分離,如下所示

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

from pandas.plotting import andrews_curves

# Import

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")

df.drop(['cars', 'carname'], axis=1, inplace=True)

# Plot

plt.figure(figsize=(12,9), dpi= 80)

andrews_curves(df, 'cyl', colormap='Set1')

# Lighten borders

plt.gca().spines["top"].set_alpha(0)

plt.gca().spines["bottom"].set_alpha(.3)

plt.gca().spines["right"].set_alpha(0)

plt.gca().spines["left"].set_alpha(.3)

plt.title('Andrews Curves of mtcars', fontsize=22)

plt.xlim(-3,3)

plt.grid(alpha=0.3)

plt.xticks(fontsize=12)

plt.yticks(fontsize=12)

plt.show()

7.4 平行坐标圖

平行坐标有助于可視化某個功能是否有助于有效地隔離組。如果進行隔離,則該功能可能在預測該組時非常有用。

python時間序列可視化_TOP50 Python可視化經典案例下(附源碼,建議收藏)

from pandas.plotting import parallel_coordinates

# Import Data

df_final = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/diamonds_filter.csv")

# Plot

plt.figure(figsize=(12,9), dpi= 80)

parallel_coordinates(df_final, 'cut', colormap='Dark2')

# Lighten borders

plt.gca().spines["top"].set_alpha(0)

plt.gca().spines["bottom"].set_alpha(.3)

plt.gca().spines["right"].set_alpha(0)

plt.gca().spines["left"].set_alpha(.3)

plt.title('Parallel Coordinated of Diamonds', fontsize=22)

plt.grid(alpha=0.3)

plt.xticks(fontsize=12)

plt.yticks(fontsize=12)

plt.show()