99精品伊人亚洲|最近国产中文炮友|九草在线视频支援|AV网站大全最新|美女黄片免费观看|国产精品资源视频|精彩无码视频一区|91大神在线后入|伊人终合在线播放|久草综合久久中文

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

在數(shù)據(jù)分析和可視化中最有用的50個(gè)Matplotlib圖表

電子工程師 ? 來源:lq ? 2018-12-28 09:30 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

本文為 Python數(shù)據(jù)之道(ID:PyDataRoad)作者投稿。Lemon,氣候變化及新能源領(lǐng)域從業(yè)者,跨界玩 Python,秉承“讓數(shù)據(jù)更有價(jià)值”的理念,希望能透過數(shù)據(jù)感知世界。

本文總結(jié)了 Matplotlib 以及 Seaborn 用的最多的 50 個(gè)圖形,掌握這些圖形的繪制,對(duì)于數(shù)據(jù)分析的可視化有莫大的作用,強(qiáng)烈推薦大家閱讀后續(xù)內(nèi)容。

在數(shù)據(jù)分析和可視化中最有用的 50 個(gè) Matplotlib 圖表。 這些圖表列表允許您使用 python 的 matplotlib 和 seaborn 庫選擇要顯示的可視化對(duì)象。

介紹

這些圖表根據(jù)可視化目標(biāo)的 7 個(gè)不同情景進(jìn)行分組。 例如,如果要想象兩個(gè)變量之間的關(guān)系,請(qǐng)查看“關(guān)聯(lián)”部分下的圖表。 或者,如果您想要顯示值如何隨時(shí)間變化,請(qǐng)查看“變化”部分,依此類推。

有效圖表的重要特征:

在不歪曲事實(shí)的情況下傳達(dá)正確和必要的信息。

設(shè)計(jì)簡(jiǎn)單,您不必太費(fèi)力就能理解它。

從審美角度支持信息而不是掩蓋信息。

信息沒有超負(fù)荷。

準(zhǔn)備工作

在代碼運(yùn)行前先引入下面的設(shè)置內(nèi)容。 當(dāng)然,單獨(dú)的圖表,可以重新設(shè)置顯示要素。

# !pip install brewer2mpl

import numpy as np

import pandas as pd

import matplotlib as mpl

import matplotlib.pyplot as plt

import seaborn as sns

import warnings; warnings.filterwarnings(action='once')

large = 22; med = 16; small = 12

params = {'axes.titlesize': large,

'legend.fontsize': med,

'figure.figsize': (16, 10),

'axes.labelsize': med,

'axes.titlesize': med,

'xtick.labelsize': med,

'ytick.labelsize': med,

'figure.titlesize': large}

plt.rcParams.update(params)

plt.style.use('seaborn-whitegrid')

sns.set_style("white")

%matplotlib inline

# Version

print(mpl.__version__) #> 3.0.0

print(sns.__version__) #> 0.9.0

3.0.2

0.9.0

一、關(guān)聯(lián) (Correlation)

關(guān)聯(lián)圖表用于可視化 2 個(gè)或更多變量之間的關(guān)系。 也就是說,一個(gè)變量如何相對(duì)于另一個(gè)變化。

1 散點(diǎn)圖(Scatter plot)

散點(diǎn)圖是用于研究?jī)蓚€(gè)變量之間關(guān)系的經(jīng)典的和基本的圖表。 如果數(shù)據(jù)中有多個(gè)組,則可能需要以不同顏色可視化每個(gè)組。 在 matplotlib 中,您可以使用plt.scatterplot()方便地執(zhí)行此操作。

# Import dataset

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

# Prepare Data

# Create as many colors as there are unique midwest['category']

categories = np.unique(midwest['category'])

colors = [plt.cm.tab10(i/float(len(categories)-1)) for i in range(len(categories))]

# Draw Plot for Each Category

plt.figure(figsize=(16, 10), dpi= 80, facecolor='w', edgecolor='k')

for i, category in enumerate(categories):

plt.scatter('area', 'poptotal',

data=midwest.loc[midwest.category==category, :],

s=20, cmap=colors[i], label=str(category))

# "c=" 修改為 "cmap=",Python數(shù)據(jù)之道 備注

# Decorations

plt.gca().set(xlim=(0.0, 0.1), ylim=(0, 90000),

xlabel='Area', ylabel='Population')

plt.xticks(fontsize=12); plt.yticks(fontsize=12)

plt.title("Scatterplot of Midwest Area vs Population", fontsize=22)

plt.legend(fontsize=12)

plt.show()

pIYBAFwlfa6ABDoQAACpWCb5Cbc580.png

圖1

2 帶邊界的氣泡圖(Bubble plot with Encircling)

有時(shí),您希望在邊界內(nèi)顯示一組點(diǎn)以強(qiáng)調(diào)其重要性。 在這個(gè)例子中,你從數(shù)據(jù)框中獲取記錄,并用下面代碼中描述的encircle()來使邊界顯示出來。

from matplotlib import patches

from scipy.spatial importConvexHull

import warnings; warnings.simplefilter('ignore')

sns.set_style("white")

# Step 1: Prepare Data

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

# As many colors as there are unique midwest['category']

categories = np.unique(midwest['category'])

colors = [plt.cm.tab10(i/float(len(categories)-1)) for i in range(len(categories))]

# Step 2: Draw Scatterplot with unique color for each category

fig = plt.figure(figsize=(16, 10), dpi= 80, facecolor='w', edgecolor='k')

for i, category in enumerate(categories):

plt.scatter('area', 'poptotal', data=midwest.loc[midwest.category==category, :],

s='dot_size', cmap=colors[i], label=str(category), edgecolors='black', linewidths=.5)

# "c=" 修改為 "cmap=",Python數(shù)據(jù)之道 備注

# Step 3: Encircling

# https://stackoverflow.com/questions/44575681/how-do-i-encircle-different-data-sets-in-scatter-plot

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

ifnot ax: ax=plt.gca()

p = np.c_[x,y]

hull = ConvexHull(p)

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

ax.add_patch(poly)

# Select data to be encircled

midwest_encircle_data = midwest.loc[midwest.state=='IN', :]

# Draw polygon surrounding vertices

encircle(midwest_encircle_data.area, midwest_encircle_data.poptotal, ec="k", fc="gold", alpha=0.1)

encircle(midwest_encircle_data.area, midwest_encircle_data.poptotal, ec="firebrick", fc="none", linewidth=1.5)

# Step 4: Decorations

plt.gca().set(xlim=(0.0, 0.1), ylim=(0, 90000),

xlabel='Area', ylabel='Population')

plt.xticks(fontsize=12); plt.yticks(fontsize=12)

plt.title("Bubble Plot with Encircling", fontsize=22)

plt.legend(fontsize=12)

plt.show()

圖2

3 帶線性回歸最佳擬合線的散點(diǎn)圖 (Scatter plot with linear regression line of best fit)

如果你想了解兩個(gè)變量如何相互改變,那么最佳擬合線就是常用的方法。 下圖顯示了數(shù)據(jù)中各組之間最佳擬合線的差異。 要禁用分組并僅為整個(gè)數(shù)據(jù)集繪制一條最佳擬合線,請(qǐng)從下面的sns.lmplot()調(diào)用中刪除hue='cyl'參數(shù)。

# Import Data

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

df_select = df.loc[df.cyl.isin([4,8]), :]

# Plot

sns.set_style("white")

gridobj = sns.lmplot(x="displ", y="hwy", hue="cyl", data=df_select,

height=7, aspect=1.6, robust=True, palette='tab10',

scatter_kws=dict(s=60, linewidths=.7, edgecolors='black'))

# Decorations

gridobj.set(xlim=(0.5, 7.5), ylim=(0, 50))

plt.title("Scatterplot with line of best fit grouped by number of cylinders", fontsize=20)

plt.show()

圖3

針對(duì)每列繪制線性回歸線

或者,可以在其每列中顯示每個(gè)組的最佳擬合線。 可以通過在sns.lmplot()中設(shè)置col=groupingcolumn參數(shù)來實(shí)現(xiàn),如下:

# Import Data

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

df_select = df.loc[df.cyl.isin([4,8]), :]

# Each line in its own column

sns.set_style("white")

gridobj = sns.lmplot(x="displ", y="hwy",

data=df_select,

height=7,

robust=True,

palette='Set1',

col="cyl",

scatter_kws=dict(s=60, linewidths=.7, edgecolors='black'))

# Decorations

gridobj.set(xlim=(0.5, 7.5), ylim=(0, 50))

plt.show()

圖3-2

4 抖動(dòng)圖 (Jittering with stripplot)

通常,多個(gè)數(shù)據(jù)點(diǎn)具有完全相同的 X 和 Y 值。 結(jié)果,多個(gè)點(diǎn)繪制會(huì)重疊并隱藏。 為避免這種情況,請(qǐng)將數(shù)據(jù)點(diǎn)稍微抖動(dòng),以便您可以直觀地看到它們。 使用 seaborn 的stripplot()很方便實(shí)現(xiàn)這個(gè)功能。

# Import Data

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

# Draw Stripplot

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

sns.stripplot(df.cty, df.hwy, jitter=0.25, size=8, ax=ax, linewidth=.5)

# Decorations

plt.title('Use jittered plots to avoid overlapping of points', fontsize=22)

plt.show()

圖4

5 計(jì)數(shù)圖 (Counts Plot)

避免點(diǎn)重疊問題的另一個(gè)選擇是增加點(diǎn)的大小,這取決于該點(diǎn)中有多少點(diǎn)。 因此,點(diǎn)的大小越大,其周圍的點(diǎn)的集中度越高。

# Import Data

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

df_counts = df.groupby(['hwy', 'cty']).size().reset_index(name='counts')

# Draw Stripplot

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

sns.stripplot(df_counts.cty, df_counts.hwy, size=df_counts.counts*2, ax=ax)

# Decorations

plt.title('Counts Plot - Size of circle is bigger as more points overlap', fontsize=22)

plt.show()

圖5

6 邊緣直方圖 (Marginal Histogram)

邊緣直方圖具有沿 X 和 Y 軸變量的直方圖。 這用于可視化 X 和 Y 之間的關(guān)系以及單獨(dú)的 X 和 Y 的單變量分布。 這種圖經(jīng)常用于探索性數(shù)據(jù)分析(EDA)。

圖6

7 邊緣箱形圖 (Marginal Boxplot)

邊緣箱圖與邊緣直方圖具有相似的用途。 然而,箱線圖有助于精確定位 X 和 Y 的中位數(shù)、第25和第75百分位數(shù)。

圖7

8 相關(guān)圖 (Correllogram)

相關(guān)圖用于直觀地查看給定數(shù)據(jù)框(或二維數(shù)組)中所有可能的數(shù)值變量對(duì)之間的相關(guān)度量。

# Import Dataset

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

# Plot

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

sns.heatmap(df.corr(), xticklabels=df.corr().columns, yticklabels=df.corr().columns, cmap='RdYlGn', center=0, annot=True)

# Decorations

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

plt.xticks(fontsize=12)

plt.yticks(fontsize=12)

plt.show()

圖8

9 矩陣圖 (Pairwise Plot)

矩陣圖是探索性分析中的最愛,用于理解所有可能的數(shù)值變量對(duì)之間的關(guān)系。 它是雙變量分析的必備工具。

# Load Dataset

df = sns.load_dataset('iris')

# Plot

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

sns.pairplot(df, kind="scatter", hue="species", plot_kws=dict(s=80, edgecolor="white", linewidth=2.5))

plt.show()

圖9

# Load Dataset

df = sns.load_dataset('iris')

# Plot

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

sns.pairplot(df, kind="reg", hue="species")

plt.show()

圖9-2

二、偏差 (Deviation)

10 發(fā)散型條形圖 (Diverging Bars)

如果您想根據(jù)單個(gè)指標(biāo)查看項(xiàng)目的變化情況,并可視化此差異的順序和數(shù)量,那么散型條形圖 (Diverging Bars) 是一個(gè)很好的工具。 它有助于快速區(qū)分?jǐn)?shù)據(jù)中組的性能,并且非常直觀,并且可以立即傳達(dá)這一點(diǎn)。

# Prepare Data

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

x = df.loc[:, ['mpg']]

df['mpg_z'] = (x - x.mean())/x.std()

df['colors'] = ['red'if x < 0else'green'for x in df['mpg_z']]

df.sort_values('mpg_z', inplace=True)

df.reset_index(inplace=True)

# Draw plot

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

plt.hlines(y=df.index, xmin=0, xmax=df.mpg_z, color=df.colors, alpha=0.4, linewidth=5)

# Decorations

plt.gca().set(ylabel='$Model$', xlabel='$Mileage$')

plt.yticks(df.index, df.cars, fontsize=12)

plt.title('Diverging Bars of Car Mileage', fontdict={'size':20})

plt.grid(linestyle='--', alpha=0.5)

plt.show()

圖10

11 發(fā)散型文本 (Diverging Texts)

發(fā)散型文本 (Diverging Texts)與發(fā)散型條形圖 (Diverging Bars)相似,如果你想以一種漂亮和可呈現(xiàn)的方式顯示圖表中每個(gè)項(xiàng)目的價(jià)值,就可以使用這種方法。

# Prepare Data

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

x = df.loc[:, ['mpg']]

df['mpg_z'] = (x - x.mean())/x.std()

df['colors'] = ['red'if x < 0else'green'for x in df['mpg_z']]

df.sort_values('mpg_z', inplace=True)

df.reset_index(inplace=True)

# Draw plot

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

plt.hlines(y=df.index, xmin=0, xmax=df.mpg_z)

for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z):

t = plt.text(x, y, round(tex, 2), horizontalalignment='right'if x < 0else'left',

verticalalignment='center', fontdict={'color':'red'if x < 0else'green', 'size':14})

# Decorations

plt.yticks(df.index, df.cars, fontsize=12)

plt.title('Diverging Text Bars of Car Mileage', fontdict={'size':20})

plt.grid(linestyle='--', alpha=0.5)

plt.xlim(-2.5, 2.5)

plt.show()

圖11

12 發(fā)散型包點(diǎn)圖 (Diverging Dot Plot)

發(fā)散型包點(diǎn)圖 (Diverging Dot Plot)也類似于發(fā)散型條形圖 (Diverging Bars)。 然而,與發(fā)散型條形圖 (Diverging Bars)相比,條的缺失減少了組之間的對(duì)比度和差異。

# Prepare Data

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

x = df.loc[:, ['mpg']]

df['mpg_z'] = (x - x.mean())/x.std()

df['colors'] = ['red'if x < 0else'darkgreen'for x in df['mpg_z']]

df.sort_values('mpg_z', inplace=True)

df.reset_index(inplace=True)

# Draw plot

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

plt.scatter(df.mpg_z, df.index, s=450, alpha=.6, color=df.colors)

for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z):

t = plt.text(x, y, round(tex, 1), horizontalalignment='center',

verticalalignment='center', fontdict={'color':'white'})

# Decorations

# 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.yticks(df.index, df.cars)

plt.title('Diverging Dotplot of Car Mileage', fontdict={'size':20})

plt.xlabel('$Mileage$')

plt.grid(linestyle='--', alpha=0.5)

plt.xlim(-2.5, 2.5)

plt.show()

圖12

13 帶標(biāo)記的發(fā)散型棒棒糖圖 (Diverging Lollipop Chart with Markers)

帶標(biāo)記的棒棒糖圖通過強(qiáng)調(diào)您想要引起注意的任何重要數(shù)據(jù)點(diǎn)并在圖表中適當(dāng)?shù)亟o出推理,提供了一種對(duì)差異進(jìn)行可視化的靈活方式。

圖13

14 面積圖 (Area Chart)

通過對(duì)軸和線之間的區(qū)域進(jìn)行著色,面積圖不僅強(qiáng)調(diào)峰和谷,而且還強(qiáng)調(diào)高點(diǎn)和低點(diǎn)的持續(xù)時(shí)間。 高點(diǎn)持續(xù)時(shí)間越長(zhǎng),線下面積越大。

import numpy as np

import pandas as pd

# Prepare Data

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv", parse_dates=['date']).head(100)

x = np.arange(df.shape[0])

y_returns = (df.psavert.diff().fillna(0)/df.psavert.shift(1)).fillna(0) * 100

# Plot

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

plt.fill_between(x[1:], y_returns[1:], 0, where=y_returns[1:] >= 0, facecolor='green', interpolate=True, alpha=0.7)

plt.fill_between(x[1:], y_returns[1:], 0, where=y_returns[1:] <= 0, facecolor='red', interpolate=True, alpha=0.7)

# Annotate

plt.annotate('Peak 1975', xy=(94.0, 21.0), xytext=(88.0, 28),

bbox=dict(boxstyle='square', fc='firebrick'),

arrowprops=dict(facecolor='steelblue', shrink=0.05), fontsize=15, color='white')

# Decorations

xtickvals = [str(m)[:3].upper()+"-"+str(y) for y,m in zip(df.date.dt.year, df.date.dt.month_name())]

plt.gca().set_xticks(x[::6])

plt.gca().set_xticklabels(xtickvals[::6], rotation=90, fontdict={'horizontalalignment': 'center', 'verticalalignment': 'center_baseline'})

plt.ylim(-35,35)

plt.xlim(1,100)

plt.title("Month Economics Return %", fontsize=22)

plt.ylabel('Monthly returns %')

plt.grid(alpha=0.5)

plt.show()

pIYBAFwlfbqAZ8_ZAAD1NwcQOrM779.png

圖14

三、排序 (Ranking)

15 有序條形圖 (Ordered Bar Chart)

有序條形圖有效地傳達(dá)了項(xiàng)目的排名順序。 但是,在圖表上方添加度量標(biāo)準(zhǔn)的值,用戶可以從圖表本身獲取精確信息。

pIYBAFwlfbqAXc2_AADGW3M66cg319.png

圖15

16 棒棒糖圖 (Lollipop Chart)

棒棒糖圖表以一種視覺上令人愉悅的方式提供與有序條形圖類似的目的。

# Prepare Data

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

df = df_raw[['cty', 'manufacturer']].groupby('manufacturer').apply(lambda x: x.mean())

df.sort_values('cty', inplace=True)

df.reset_index(inplace=True)

# Draw plot

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

ax.vlines(x=df.index, ymin=0, ymax=df.cty, color='firebrick', alpha=0.7, linewidth=2)

ax.scatter(x=df.index, y=df.cty, s=75, color='firebrick', alpha=0.7)

# Title, Label, Ticks and Ylim

ax.set_title('Lollipop Chart for Highway Mileage', fontdict={'size':22})

ax.set_ylabel('Miles Per Gallon')

ax.set_xticks(df.index)

ax.set_xticklabels(df.manufacturer.str.upper(), rotation=60, fontdict={'horizontalalignment': 'right', 'size':12})

ax.set_ylim(0, 30)

# Annotate

for row in df.itertuples():

ax.text(row.Index, row.cty+.5, s=round(row.cty, 2), horizontalalignment= 'center', verticalalignment='bottom', fontsize=14)

plt.show()

pIYBAFwlfbqAVFYSAAC4_BojaLc036.png

圖16

17 包點(diǎn)圖 (Dot Plot)

包點(diǎn)圖表傳達(dá)了項(xiàng)目的排名順序,并且由于它沿水平軸對(duì)齊,因此您可以更容易地看到點(diǎn)彼此之間的距離。

# Prepare Data

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

df = df_raw[['cty', 'manufacturer']].groupby('manufacturer').apply(lambda x: x.mean())

df.sort_values('cty', inplace=True)

df.reset_index(inplace=True)

# Draw plot

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

ax.hlines(y=df.index, xmin=11, xmax=26, color='gray', alpha=0.7, linewidth=1, linestyles='dashdot')

ax.scatter(y=df.index, x=df.cty, s=75, color='firebrick', alpha=0.7)

# Title, Label, Ticks and Ylim

ax.set_title('Dot Plot for Highway Mileage', fontdict={'size':22})

ax.set_xlabel('Miles Per Gallon')

ax.set_yticks(df.index)

ax.set_yticklabels(df.manufacturer.str.title(), fontdict={'horizontalalignment': 'right'})

ax.set_xlim(10, 27)

plt.show()

pIYBAFwlfbuADGMlAADRCiMzeEk445.png

圖17

18 坡度圖 (Slope Chart)

坡度圖最適合比較給定人/項(xiàng)目的“前”和“后”位置。

pIYBAFwlfbyAA7U3AACsUPQg8Gw297.png

圖18

19 啞鈴圖 (Dumbbell Plot)

啞鈴圖表傳達(dá)了各種項(xiàng)目的“前”和“后”位置以及項(xiàng)目的等級(jí)排序。 如果您想要將特定項(xiàng)目/計(jì)劃對(duì)不同對(duì)象的影響可視化,那么它非常有用。

pIYBAFwlfbyAKgc2AACnU8vvL9I633.png

圖19

四、分布 (Distribution)

20 連續(xù)變量的直方圖 (Histogram for Continuous Variable)

直方圖顯示給定變量的頻率分布。 下面的圖表示基于類型變量對(duì)頻率條進(jìn)行分組,從而更好地了解連續(xù)變量和類型變量。

# Import Data

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

# Prepare data

x_var = 'displ'

groupby_var = 'class'

df_agg = df.loc[:, [x_var, groupby_var]].groupby(groupby_var)

vals = [df[x_var].values.tolist() for i, df in df_agg]

# Draw

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

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

n, bins, patches = plt.hist(vals, 30, stacked=True, density=False, color=colors[:len(vals)])

# Decoration

plt.legend({group:col for group, col in zip(np.unique(df[groupby_var]).tolist(), colors[:len(vals)])})

plt.title(f"Stacked Histogram of ${x_var}$ colored by ${groupby_var}$", fontsize=22)

plt.xlabel(x_var)

plt.ylabel("Frequency")

plt.ylim(0, 25)

plt.xticks(ticks=bins[::3], labels=[round(b,1) for b in bins[::3]])

plt.show()

pIYBAFwlfb2AHrLbAACU8sE0OjA940.png

圖20

21 類型變量的直方圖 (Histogram for Categorical Variable)

類型變量的直方圖顯示該變量的頻率分布。 通過對(duì)條形圖進(jìn)行著色,可以將分布與表示顏色的另一個(gè)類型變量相關(guān)聯(lián)。

# Import Data

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

# Prepare data

x_var = 'manufacturer'

groupby_var = 'class'

df_agg = df.loc[:, [x_var, groupby_var]].groupby(groupby_var)

vals = [df[x_var].values.tolist() for i, df in df_agg]

# Draw

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

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

n, bins, patches = plt.hist(vals, df[x_var].unique().__len__(), stacked=True, density=False, color=colors[:len(vals)])

# Decoration

plt.legend({group:col for group, col in zip(np.unique(df[groupby_var]).tolist(), colors[:len(vals)])})

plt.title(f"Stacked Histogram of ${x_var}$ colored by ${groupby_var}$", fontsize=22)

plt.xlabel(x_var)

plt.ylabel("Frequency")

plt.ylim(0, 40)

plt.xticks(ticks=bins, labels=np.unique(df[x_var]).tolist(), rotation=90, horizontalalignment='left')

plt.show()

pIYBAFwlfb2Aagu3AAC9iMbu8io145.png

圖21

22 密度圖 (Density Plot)

密度圖是一種常用工具,用于可視化連續(xù)變量的分布。 通過“響應(yīng)”變量對(duì)它們進(jìn)行分組,您可以檢查 X 和 Y 之間的關(guān)系。以下情況用于表示目的,以描述城市里程的分布如何隨著汽缸數(shù)的變化而變化。

# Import Data

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

# Draw Plot

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

sns.kdeplot(df.loc[df['cyl'] == 4, "cty"], shade=True, color="g", label="Cyl=4", alpha=.7)

sns.kdeplot(df.loc[df['cyl'] == 5, "cty"], shade=True, color="deeppink", label="Cyl=5", alpha=.7)

sns.kdeplot(df.loc[df['cyl'] == 6, "cty"], shade=True, color="dodgerblue", label="Cyl=6", alpha=.7)

sns.kdeplot(df.loc[df['cyl'] == 8, "cty"], shade=True, color="orange", label="Cyl=8", alpha=.7)

# Decoration

plt.title('Density Plot of City Mileage by n_Cylinders', fontsize=22)

plt.legend()

plt.show()

pIYBAFwlfb6AE9LUAAB8_vg5IPQ769.png

圖22

23 直方密度線圖 (Density Curves with Histogram)

帶有直方圖的密度曲線匯集了兩個(gè)圖所傳達(dá)的集體信息,因此您可以將它們放在一個(gè)圖中而不是兩個(gè)圖中。

# Import Data

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

# Draw Plot

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

sns.distplot(df.loc[df['class'] == 'compact', "cty"], color="dodgerblue", label="Compact", hist_kws={'alpha':.7}, kde_kws={'linewidth':3})

sns.distplot(df.loc[df['class'] == 'suv', "cty"], color="orange", label="SUV", hist_kws={'alpha':.7}, kde_kws={'linewidth':3})

sns.distplot(df.loc[df['class'] == 'minivan', "cty"], color="g", label="minivan", hist_kws={'alpha':.7}, kde_kws={'linewidth':3})

plt.ylim(0, 0.35)

# Decoration

plt.title('Density Plot of City Mileage by Vehicle Type', fontsize=22)

plt.legend()

plt.show()

pIYBAFwlfb-AJj12AACctn50F3Q759.png

圖23

24 Joy Plot

Joy Plot允許不同組的密度曲線重疊,這是一種可視化大量分組數(shù)據(jù)的彼此關(guān)系分布的好方法。 它看起來很悅目,并清楚地傳達(dá)了正確的信息。 它可以使用基于 matplotlib 的 joypy 包輕松構(gòu)建。 (『Python數(shù)據(jù)之道』注:需要安裝 joypy 庫)

# !pip install joypy

# Python數(shù)據(jù)之道 備注

import joypy

# Import Data

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

# Draw Plot

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

fig, axes = joypy.joyplot(mpg, column=['hwy', 'cty'], by="class", ylim='own', figsize=(14,10))

# Decoration

plt.title('Joy Plot of City and Highway Mileage by Class', fontsize=22)

plt.show()

pIYBAFwlfb-Aa5qXAAC8kNSI9U0998.png

圖24

25 分布式包點(diǎn)圖 (Distributed Dot Plot)

分布式包點(diǎn)圖顯示按組分割的點(diǎn)的單變量分布。 點(diǎn)數(shù)越暗,該區(qū)域的數(shù)據(jù)點(diǎn)集中度越高。 通過對(duì)中位數(shù)進(jìn)行不同著色,組的真實(shí)定位立即變得明顯。

pIYBAFwlfcCAcfJaAACh5DnnFEU253.png

圖25

26 箱形圖 (Box Plot)

箱形圖是一種可視化分布的好方法,記住中位數(shù)、第25個(gè)第45個(gè)四分位數(shù)和異常值。 但是,您需要注意解釋可能會(huì)扭曲該組中包含的點(diǎn)數(shù)的框的大小。 因此,手動(dòng)提供每個(gè)框中的觀察數(shù)量可以幫助克服這個(gè)缺點(diǎn)。

例如,左邊的前兩個(gè)框具有相同大小的框,即使它們的值分別是5和47。 因此,寫入該組中的觀察數(shù)量是必要的。

# Import Data

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

# Draw Plot

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

sns.boxplot(x='class', y='hwy', data=df, notch=False)

# Add N Obs inside boxplot (optional)

def add_n_obs(df,group_col,y):

medians_dict = {grp[0]:grp[1][y].median() for grp in df.groupby(group_col)}

xticklabels = [x.get_text() for x in plt.gca().get_xticklabels()]

n_obs = df.groupby(group_col)[y].size().values

for (x, xticklabel), n_ob in zip(enumerate(xticklabels), n_obs):

plt.text(x, medians_dict[xticklabel]*1.01, "#obs : "+str(n_ob), horizontalalignment='center', fontdict={'size':14}, color='white')

add_n_obs(df,group_col='class',y='hwy')

# Decoration

plt.title('Box Plot of Highway Mileage by Vehicle Class', fontsize=22)

plt.ylim(10, 40)

plt.show()

圖26

27 包點(diǎn)+箱形圖 (Dot + Box Plot)

包點(diǎn)+箱形圖 (Dot + Box Plot)傳達(dá)類似于分組的箱形圖信息。 此外,這些點(diǎn)可以了解每組中有多少數(shù)據(jù)點(diǎn)。

# Import Data

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

# Draw Plot

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

sns.boxplot(x='class', y='hwy', data=df, hue='cyl')

sns.stripplot(x='class', y='hwy', data=df, color='black', size=3, jitter=1)

for i in range(len(df['class'].unique())-1):

plt.vlines(i+.5, 10, 45, linestyles='solid', colors='gray', alpha=0.2)

# Decoration

plt.title('Box Plot of Highway Mileage by Vehicle Class', fontsize=22)

plt.legend(title='Cylinders')

plt.show()

pIYBAFwlfcGASpPYAACpABqsL_U411.png

圖27

28 小提琴圖 (Violin Plot)

小提琴圖是箱形圖在視覺上令人愉悅的替代品。 小提琴的形狀或面積取決于它所持有的觀察次數(shù)。 但是,小提琴圖可能更難以閱讀,并且在專業(yè)設(shè)置中不常用。

# Import Data

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

# Draw Plot

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

sns.violinplot(x='class', y='hwy', data=df, scale='width', inner='quartile')

# Decoration

plt.title('Violin Plot of Highway Mileage by Vehicle Class', fontsize=22)

plt.show()

圖28

29 人口金字塔 (Population Pyramid)

人口金字塔可用于顯示由數(shù)量排序的組的分布。 或者它也可以用于顯示人口的逐級(jí)過濾,因?yàn)樗谙旅嬗糜陲@示有多少人通過營(yíng)銷渠道的每個(gè)階段。

# Read data

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

# Draw Plot

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

group_col = 'Gender'

order_of_bars = df.Stage.unique()[::-1]

colors = [plt.cm.Spectral(i/float(len(df[group_col].unique())-1)) for i in range(len(df[group_col].unique()))]

for c, group in zip(colors, df[group_col].unique()):

sns.barplot(x='Users', y='Stage', data=df.loc[df[group_col]==group, :], order=order_of_bars, color=c, label=group)

# Decorations

plt.xlabel("$Users$")

plt.ylabel("Stage of Purchase")

plt.yticks(fontsize=12)

plt.title("Population Pyramid of the Marketing Funnel", fontsize=22)

plt.legend()

plt.show()

pIYBAFwlfcKANszhAADjIBVE56U852.png

圖29

30 分類圖 (Categorical Plots)

由 seaborn庫 提供的分類圖可用于可視化彼此相關(guān)的2個(gè)或更多分類變量的計(jì)數(shù)分布。

# Load Dataset

titanic = sns.load_dataset("titanic")

# Plot

g = sns.catplot("alive", col="deck", col_wrap=4,

data=titanic[titanic.deck.notnull()],

kind="count", height=3.5, aspect=.8,

palette='tab20')

fig.suptitle('sf')

plt.show()

pIYBAFwlfcKAaqR7AAAhDb5s370703.png

圖30

# Load Dataset

titanic = sns.load_dataset("titanic")

# Plot

sns.catplot(x="age", y="embark_town",

hue="sex", col="class",

data=titanic[titanic.embark_town.notnull()],

orient="h", height=5, aspect=1, palette="tab10",

kind="violin", dodge=True, cut=0, bw=.2)

pIYBAFwlfcOAMqh4AACF2zufVq0983.png

圖30-2

五、組成 (Composition)

31 華夫餅圖 (Waffle Chart)

可以使用 pywaffle包 創(chuàng)建華夫餅圖,并用于顯示更大群體中的組的組成。

(『Python數(shù)據(jù)之道』注:需要安裝 pywaffle 庫)

#! pip install pywaffle

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

from pywaffle importWaffle

# Import

df_raw = pd.read_csv("https://github.com/selva86/datasets/raw/master/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)

)

pIYBAFwlfcSAExQbAACFYd_Z63M629.png

圖31

pIYBAFwlfcSAW6DCAAIX2b5HHwM395.png

圖31-2

32 餅圖 (Pie Chart)

餅圖是顯示組成的經(jīng)典方式。 然而,現(xiàn)在通常不建議使用它,因?yàn)轲W餅部分的面積有時(shí)會(huì)變得誤導(dǎo)。 因此,如果您要使用餅圖,強(qiáng)烈建議明確記下餅圖每個(gè)部分的百分比或數(shù)字。

# Import

df_raw = pd.read_csv("https://github.com/selva86/datasets/raw/master/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))

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

plt.ylabel("")

plt.show()

pIYBAFwlfcWAFjDkAAB14-989Sk717.png

圖32

pIYBAFwlfcWATZGAAABgBcRabjc767.png

圖32-2

33 樹形圖 (Treemap)

樹形圖類似于餅圖,它可以更好地完成工作而不會(huì)誤導(dǎo)每個(gè)組的貢獻(xiàn)。

(『Python數(shù)據(jù)之道』注:需要安裝 squarify 庫)

# pip install squarify

import squarify

# Import Data

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

# Prepare Data

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

labels = df.apply(lambda x: str(x[0]) + " (" + 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()

pIYBAFwlfcWAOjKoAABCheEWLN0869.png

圖33

34 條形圖 (Bar Chart)

條形圖是基于計(jì)數(shù)或任何給定指標(biāo)可視化項(xiàng)目的經(jīng)典方式。 在下面的圖表中,我為每個(gè)項(xiàng)目使用了不同的顏色,但您通??赡芟M麨樗许?xiàng)目選擇一種顏色,除非您按組對(duì)其進(jìn)行著色。 顏色名稱存儲(chǔ)在下面代碼中的all_colors中。 您可以通過在plt.plot()中設(shè)置顏色參數(shù)來更改條的顏色。

import random

# Import Data

df_raw = pd.read_csv("https://github.com/selva86/datasets/raw/master/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()

pIYBAFwlfcaAA8sPAACul5wZ6o0959.png

圖34

六、變化 (Change)

35 時(shí)間序列圖 (Time Series Plot)

時(shí)間序列圖用于顯示給定度量隨時(shí)間變化的方式。 在這里,您可以看到 1949 年至 1969 年間航空客運(yùn)量的變化情況。

# 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()

pIYBAFwlfceAH4BPAAChBS5Wym8263.png

圖35

36 帶波峰波谷標(biāo)記的時(shí)序圖 (Time Series with Peaks and Troughs Annotated)

下面的時(shí)間序列繪制了所有峰值和低谷,并注釋了所選特殊事件的發(fā)生。

pIYBAFwlfciAJKpUAADhBtS4z2g978.png

圖36

37 自相關(guān)和部分自相關(guān)圖 (Autocorrelation (ACF) and Partial Autocorrelation (PACF) Plot)

自相關(guān)圖(ACF 圖)顯示時(shí)間序列與其自身滯后的相關(guān)性。 每條垂直線(在自相關(guān)圖上)表示系列與滯后 0 之間的滯后之間的相關(guān)性。圖中的藍(lán)色陰影區(qū)域是顯著性水平。 那些位于藍(lán)線之上的滯后是顯著的滯后。

那么如何解讀呢?

對(duì)于空乘旅客,我們看到多達(dá) 14 個(gè)滯后跨越藍(lán)線,因此非常重要。 這意味著,14 年前的航空旅客交通量對(duì)今天的交通狀況有影響。

PACF 在另一方面顯示了任何給定滯后(時(shí)間序列)與當(dāng)前序列的自相關(guān),但是刪除了滯后的貢獻(xiàn)。

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()

pIYBAFwlfciAGrhPAAB4cIuxLdA343.png

圖37

38 交叉相關(guān)圖 (Cross Correlation plot)

交叉相關(guān)圖顯示了兩個(gè)時(shí)間序列相互之間的滯后。

pIYBAFwlfcmAMF4iAAArsqaFBvQ236.png

圖38

39 時(shí)間序列分解圖 (Time Series Decomposition Plot)

時(shí)間序列分解圖顯示時(shí)間序列分解為趨勢(shì),季節(jié)和殘差分量。

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()

pIYBAFwlfcmAeLMSAADaUuCwweE840.png

圖39

40 多個(gè)時(shí)間序列 (Multiple Time Series)

您可以繪制多個(gè)時(shí)間序列,在同一圖表上測(cè)量相同的值,如下所示。

pIYBAFwlfcqAWU6NAADOZIbV1zk250.png

圖40

41 使用輔助 Y 軸來繪制不同范圍的圖形 (Plotting with different scales using secondary Y axis)

如果要顯示在同一時(shí)間點(diǎn)測(cè)量?jī)蓚€(gè)不同數(shù)量的兩個(gè)時(shí)間序列,則可以在右側(cè)的輔助Y軸上再繪制第二個(gè)系列。

pIYBAFwlfcuAXyJ5AAD33ssNB98329.png

圖41

42 帶有誤差帶的時(shí)間序列 (Time Series with Error Bands)

如果您有一個(gè)時(shí)間序列數(shù)據(jù)集,每個(gè)時(shí)間點(diǎn)(日期/時(shí)間戳)有多個(gè)觀測(cè)值,則可以構(gòu)建帶有誤差帶的時(shí)間序列。 您可以在下面看到一些基于每天不同時(shí)間訂單的示例。 另一個(gè)關(guān)于 45 天持續(xù)到達(dá)的訂單數(shù)量的例子。

在該方法中,訂單數(shù)量的平均值由白線表示。 并且計(jì)算 95% 置信區(qū)間并圍繞均值繪制。

pIYBAFwlfcuAa68hAACjPjvptXk831.png

圖42

圖42-2

43 堆積面積圖 (Stacked Area Chart)

堆積面積圖可以直觀地顯示多個(gè)時(shí)間序列的貢獻(xiàn)程度,因此很容易相互比較。

pIYBAFwlfc2AVEu2AADrsJzaUtM460.png

圖43

44 未堆積的面積圖 (Area Chart UnStacked)

未堆積面積圖用于可視化兩個(gè)或更多個(gè)系列相對(duì)于彼此的進(jìn)度(起伏)。 在下面的圖表中,您可以清楚地看到隨著失業(yè)中位數(shù)持續(xù)時(shí)間的增加,個(gè)人儲(chǔ)蓄率會(huì)下降。 未堆積面積圖表很好地展示了這種現(xiàn)象。

# 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()

pIYBAFwlfc2Abho1AADKO290EHc878.png

圖44

45 日歷熱力圖 (Calendar Heat Map)

與時(shí)間序列相比,日歷地圖是可視化基于時(shí)間的數(shù)據(jù)的備選和不太優(yōu)選的選項(xiàng)。 雖然可以在視覺上吸引人,但數(shù)值并不十分明顯。 然而,它可以很好地描繪極端值和假日效果。

(『Python數(shù)據(jù)之道』注:需要安裝 calmap 庫)

import matplotlib as mpl

# pip install calmap

# Python數(shù)據(jù)之道 備注

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()

pIYBAFwlfc6AZ0RhAAB08d0oamU063.png

圖45

46 季節(jié)圖 (Seasonal Plot)

季節(jié)圖可用于比較上一季中同一天(年/月/周等)的時(shí)間序列。

pIYBAFwlfc6AJjhRAAD7BxKV67k666.png

圖46

七、分組 (Groups)

47 樹狀圖 (Dendrogram)

樹形圖基于給定的距離度量將相似的點(diǎn)組合在一起,并基于點(diǎn)的相似性將它們組織在樹狀鏈接中。

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()

pIYBAFwlfc-AR3OqAADhL42bdQg407.png

圖47

48 簇狀圖 (Cluster Plot)

簇狀圖 (Cluster Plot)可用于劃分屬于同一群集的點(diǎn)。 下面是根據(jù) USArrests 數(shù)據(jù)集將美國(guó)各州分為 5 組的代表性示例。 此圖使用“謀殺”和“攻擊”列作為 X 和 Y 軸。 或者,您可以將第一個(gè)到主要組件用作 X 軸和 Y 軸。

from sklearn.cluster importAgglomerativeClustering

from scipy.spatial importConvexHull

# 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):

ifnot 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()

pIYBAFwlfdCALVUWAAB2M8_pgS0042.png

圖48

49 安德魯斯曲線 (Andrews Curve)

安德魯斯曲線有助于可視化是否存在基于給定分組的數(shù)字特征的固有分組。 如果要素(數(shù)據(jù)集中的列)無法區(qū)分組(cyl),那么這些線將不會(huì)很好地隔離,如下所示。

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()

pIYBAFwlfdCADs8SAADyVghPVvE384.png

圖49

50 平行坐標(biāo) (Parallel Coordinates)

平行坐標(biāo)有助于可視化特征是否有助于有效地隔離組。 如果實(shí)現(xiàn)隔離,則該特征可能在預(yù)測(cè)該組時(shí)非常有用。

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()

pIYBAFwlfdGAe9ZFAACY_DmKxHk058.png

圖50

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • 代碼
    +關(guān)注

    關(guān)注

    30

    文章

    4900

    瀏覽量

    70802
  • 可視化
    +關(guān)注

    關(guān)注

    1

    文章

    1264

    瀏覽量

    21878
  • 數(shù)據(jù)分析
    +關(guān)注

    關(guān)注

    2

    文章

    1474

    瀏覽量

    35053

原文標(biāo)題:深度好文|Matplotlib可視化最有價(jià)值的50個(gè)圖表(附完整Python源代碼)

文章出處:【微信號(hào):rgznai100,微信公眾號(hào):rgznai100】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。

收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評(píng)論

    相關(guān)推薦
    熱點(diǎn)推薦

    七款經(jīng)久不衰的數(shù)據(jù)可視化工具!

    :對(duì)于年收益低于1億的中小型企業(yè)來說采購成本較高,但可以考慮引入FineBI的Saas版本九數(shù)云 2. Tableau 優(yōu)點(diǎn):強(qiáng)大的數(shù)據(jù)可視化功能,支持多種數(shù)據(jù)源連接和大數(shù)據(jù)分析,
    發(fā)表于 01-19 15:24

    如何使用協(xié)議分析儀進(jìn)行數(shù)據(jù)分析可視化

    使用協(xié)議分析儀進(jìn)行數(shù)據(jù)分析可視化,需結(jié)合數(shù)據(jù)捕獲、協(xié)議解碼、統(tǒng)計(jì)分析可視化工具,將原始
    發(fā)表于 07-16 14:16

    數(shù)據(jù)可視化之Python-matplotlib概述

    數(shù)據(jù)可視化(二):Python-matplotlib
    發(fā)表于 07-22 14:58

    為更快讀懂報(bào)表,我們將數(shù)據(jù)可視化

    常用圖表的基礎(chǔ)上,開發(fā)數(shù)十種高級(jí)數(shù)據(jù)可視化圖表,同時(shí)還賦予這些圖表聯(lián)動(dòng)鉆取功能,讓瀏覽者一眼看懂數(shù)據(jù)
    發(fā)表于 06-05 17:21

    只有報(bào)表直觀了,不能算真正的數(shù)據(jù)可視化

    數(shù)據(jù)鏈的直觀?主要依靠三方面的合力作用,分別是可視化圖表、智能數(shù)據(jù)分析功能、數(shù)據(jù)中心(
    發(fā)表于 07-01 17:20

    BI數(shù)據(jù)分析軟件使用指南

    存貯。二、數(shù)據(jù)可視化分析報(bào)表制作一鍵新建報(bào)表、應(yīng)用可視化圖表后,通過拖拉拽就能自定義可視化圖表
    發(fā)表于 01-04 11:00

    一般圖表做不了的分析,BI數(shù)據(jù)可視化圖表可以

    。 OurwayBI數(shù)據(jù)可視化報(bào)表 OurwayBI數(shù)據(jù)可視化報(bào)表上面兩張數(shù)據(jù)可視化報(bào)表截圖則是
    發(fā)表于 01-15 10:22

    怎么做以中國(guó)地圖為底圖的數(shù)據(jù)可視化報(bào)表?

    就該地的銷售數(shù)據(jù)進(jìn)行分析可視化展示,讓瀏覽者能立即了解該地區(qū)的具體銷售情況。浮窗效果浮窗效果我們也是常見的,比如說當(dāng)鼠標(biāo)經(jīng)過某地時(shí),就會(huì)在頁面上出現(xiàn)一個(gè)浮窗,上面可以是一
    發(fā)表于 07-06 16:07

    什么樣的數(shù)據(jù)分析軟件能讓全員自助可視化分析更絲滑?

    的大數(shù)據(jù)時(shí)代,數(shù)據(jù)可視化分析的效率、靈活自助性都將極大地影響企業(yè)的經(jīng)營(yíng)決策。在動(dòng)則千萬級(jí)、過億級(jí)的大數(shù)據(jù)量下,企業(yè)更需要一個(gè)能夠智能且高效、
    發(fā)表于 09-22 10:04

    新手必看:數(shù)據(jù)可視化圖表的選擇技巧

    立即生效BI數(shù)據(jù)分析軟件上的數(shù)據(jù)可視化圖表都是經(jīng)過提前預(yù)設(shè),打造成一個(gè)個(gè)點(diǎn)擊立即生效的圖表模板。
    發(fā)表于 09-29 09:35

    SpeedBI數(shù)據(jù)可視化工具:瀏覽器上做分析

    SpeedBI數(shù)據(jù)分析云是一種在瀏覽器上進(jìn)行數(shù)據(jù)可視化分析的工具,它能夠?qū)?b class='flag-5'>數(shù)據(jù)可視化的形式呈現(xiàn)出來,并支持多種
    發(fā)表于 08-22 10:55

    財(cái)務(wù)數(shù)據(jù)分析?奧威BI數(shù)據(jù)可視化工具很擅長(zhǎng)

    的智能財(cái)務(wù)指標(biāo)計(jì)算功能,還擁有一套標(biāo)準(zhǔn)、系統(tǒng)的財(cái)務(wù)數(shù)據(jù)分析方案,無需測(cè)試,下載即可用! 奧威BI工具+智能財(cái)務(wù)方案:輕松完成智能財(cái)務(wù)數(shù)據(jù)可視化分
    發(fā)表于 08-29 09:44

    可視化策略的數(shù)據(jù)分析

    研究者采用可視化策略(即平行坐標(biāo))的數(shù)據(jù)分析方法,更好地展示了多維材料數(shù)據(jù),可以更好地識(shí)別不同屬性之間的有用關(guān)系。
    的頭像 發(fā)表于 04-27 09:22 ?4761次閱讀
    <b class='flag-5'>可視化</b>策略的<b class='flag-5'>數(shù)據(jù)分析</b>

    用標(biāo)準(zhǔn)數(shù)據(jù)分析方案做數(shù)據(jù)可視化更省成本

    標(biāo)準(zhǔn)數(shù)據(jù)分析方案是以豐富經(jīng)驗(yàn)為基礎(chǔ),針對(duì)數(shù)據(jù)分析共性需求進(jìn)行設(shè)置的數(shù)據(jù)分析方案。在數(shù)據(jù)可視化工具上直接使用標(biāo)準(zhǔn)
    發(fā)表于 10-13 14:26 ?573次閱讀

    使用Python來收集、處理和可視化人口數(shù)據(jù)

    可視化: pandas:一個(gè)提供高性能、易用的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析工具的庫。 requests:一個(gè)簡(jiǎn)潔、優(yōu)雅的HTTP庫,用于發(fā)送網(wǎng)絡(luò)請(qǐng)求
    的頭像 發(fā)表于 06-21 17:08 ?1941次閱讀
    使用Python來收集、處理和<b class='flag-5'>可視化</b>人口<b class='flag-5'>數(shù)據(jù)</b>