Matplotlib 可视化最有价值的 14 个图表(附完整 Python 源代码)

640?wx_fmt=jpeg


本文来源 | 公众号 Python数据之道

翻译 | Lemon

作者 | Machine Learning Plus


本文总结了 Matplotlib 以及 Seaborn 用的最多的 50 个图形,掌握这些图形的绘制,对于数据分析的可视化有莫大的作用,在数据分析和可视化中最有用的 50 个 Matplotlib 图表。 这些图表列表允许您使用 python 的 matplotlib 和 seaborn 库选择要显示的可视化对象。

介绍

这些图表根据可视化目标的7个不同情景进行分组。 例如,如果要想象两个变量之间的关系,请查看“关联”部分下的图表。 或者,如果您想要显示值如何随时间变化,请查看“变化”部分,依此类推。

有效图表的重要特征:

  • 在不歪曲事实的情况下传达正确和必要的信息。

  • 设计简单,您不必太费力就能理解它。

  • 从审美角度支持信息而不是掩盖信息。

  • 信息没有超负荷。

准备工作

在代码运行前先引入下面的设置内容。 当然,单独的图表,可以重新设置显示要素。

 
 
  1. # !pip install brewer2mpl

  2. import numpy as np

  3. import pandas as pd

  4. import matplotlib as mpl

  5. import matplotlib.pyplot as plt

  6. import seaborn as sns

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


  8. large = 22; med = 16; small = 12

  9. params = {'axes.titlesize': large,

  10.          'legend.fontsize': med,

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

  12.          'axes.labelsize': med,

  13.          'axes.titlesize': med,

  14.          'xtick.labelsize': med,

  15.          'ytick.labelsize': med,

  16.          'figure.titlesize': large}

  17. plt.rcParams.update(params)

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

  19. sns.set_style("white")

  20. %matplotlib inline


  21. # Version

  22. print(mpl.__version__)  #> 3.0.0

  23. print(sns.__version__)  #> 0.9.0

 
 
  1. 3.0.2

  2. 0.9.0

一、关联 (Correlation)

关联图表用于可视化2个或更多变量之间的关系。 也就是说,一个变量如何相对于另一个变化。

1. 散点图(Scatter plot)

散点图是用于研究两个变量之间关系的经典的和基本的图表。 如果数据中有多个组,则可能需要以不同颜色可视化每个组。 在 matplotlib 中,您可以使用 plt.scatterplot() 方便地执行此操作。

 
 
  1. # Import dataset

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


  3. # Prepare Data

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

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

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


  7. # Draw Plot for Each Category

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


  9. for i, category in enumerate(categories):

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

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

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

  13.    # "c=" 修改为 "cmap=",Python数据之道 备注


  14. # Decorations

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

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


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

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

  19. plt.legend(fontsize=12)    

  20. plt.show()    

640?wx_fmt=png

图1

2. 带边界的气泡图(Bubble plot with Encircling)

有时,您希望在边界内显示一组点以强调其重要性。 在这个例子中,你从数据框中获取记录,并用下面代码中描述的 encircle() 来使边界显示出来。

 
 
  1. from matplotlib import patches

  2. from scipy.spatial import ConvexHull

  3. import warnings; warnings.simplefilter('ignore')

  4. sns.set_style("white")


  5. # Step 1: Prepare Data

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


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

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

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


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

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


  12. for i, category in enumerate(categories):

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

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

  15.    # "c=" 修改为 "cmap=",Python数据之道 备注


  16. # Step 3: Encircling

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

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

  19.    if not ax: ax=plt.gca()

  20.    p = np.c_[x,y]

  21.    hull = ConvexHull(p)

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

  23.    ax.add_patch(poly)


  24. # Select data to be encircled

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


  26. # Draw polygon surrounding vertices    

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

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


  29. # Step 4: Decorations

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

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


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

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

  34. plt.legend(fontsize=12)    

  35. plt.show()    

640?wx_fmt=png

图2

二、偏差 (Deviation)

3.  发散型条形图 (Diverging Bars)

如果您想根据单个指标查看项目的变化情况,并可视化此差异的顺序和数量,那么散型条形图 (Diverging Bars) 是一个很好的工具。 它有助于快速区分数据中组的性能,并且非常直观,并且可以立即传达这一点。

 
 
  1. # Prepare Data

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

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

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

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

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

  7. df.reset_index(inplace=True)


  8. # Draw plot

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

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


  11. # Decorations

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

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

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

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

  16. plt.show()

640?wx_fmt=png

图3

4. 发散型文本 (Diverging Texts)

发散型文本 (Diverging Texts)与发散型条形图 (Diverging Bars)相似,如果你想以一种漂亮和可呈现的方式显示图表中每个项目的价值,就可以使用这种方法。

 
 
  1. # Prepare Data

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

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

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

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

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

  7. df.reset_index(inplace=True)


  8. # Draw plot

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

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

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

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

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


  14. # Decorations    

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

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

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

  18. plt.xlim(-2.5, 2.5)

  19. plt.show()

640?wx_fmt=png

图4

三、排序 (Ranking)

5. 有序条形图 (Ordered Bar Chart)

有序条形图有效地传达了项目的排名顺序。 但是,在图表上方添加度量标准的值,用户可以从图表本身获取精确信息。

640?wx_fmt=png

图5

6. 棒棒糖图 (Lollipop Chart)

棒棒糖图表以一种视觉上令人愉悦的方式提供与有序条形图类似的目的。

 
 
  1. # Prepare Data

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

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

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

  5. df.reset_index(inplace=True)


  6. # Draw plot

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

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

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


  10. # Title, Label, Ticks and Ylim

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

  12. ax.set_ylabel('Miles Per Gallon')

  13. ax.set_xticks(df.index)

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

  15. ax.set_ylim(0, 30)


  16. # Annotate

  17. for row in df.itertuples():

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


  19. plt.show()

640?wx_fmt=png

图6

四、分布 (Distribution)

7. 连续变量的直方图 (Histogram for Continuous Variable)

直方图显示给定变量的频率分布。 下面的图表示基于类型变量对频率条进行分组,从而更好地了解连续变量和类型变量。

 
 
  1. # Import Data

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


  3. # Prepare data

  4. x_var = 'displ'

  5. groupby_var = 'class'

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

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


  8. # Draw

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

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

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


  12. # Decoration

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

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

  15. plt.xlabel(x_var)

  16. plt.ylabel("Frequency")

  17. plt.ylim(0, 25)

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

  19. plt.show()

640?wx_fmt=png

图7

8. 类型变量的直方图 (Histogram for Categorical Variable)

类型变量的直方图显示该变量的频率分布。 通过对条形图进行着色,可以将分布与表示颜色的另一个类型变量相关联。

 
 
  1. # Import Data

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


  3. # Prepare data

  4. x_var = 'manufacturer'

  5. groupby_var = 'class'

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

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


  8. # Draw

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

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

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


  12. # Decoration

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

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

  15. plt.xlabel(x_var)

  16. plt.ylabel("Frequency")

  17. plt.ylim(0, 40)

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

  19. plt.show()

640?wx_fmt=png

图8

五、组成 (Composition)

9. 华夫饼图 (Waffle Chart)

可以使用 pywaffle包 创建华夫饼图,并用于显示更大群体中的组的组成。

 
 
  1. #! pip install pywaffle

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

  3. from pywaffle import Waffle


  4. # Import

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


  6. # Prepare Data

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

  8. n_categories = df.shape[0]

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


  10. # Draw Plot and Decorate

  11. fig = plt.figure(

  12.    FigureClass=Waffle,

  13.    plots={

  14.        '111': {

  15.            'values': df['counts'],

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

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

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

  19.        },

  20.    },

  21.    rows=7,

  22.    colors=colors,

  23.    figsize=(16, 9)

  24. )

640?wx_fmt=png

图31

640?wx_fmt=png

图9

10. 饼图 (Pie Chart)

饼图是显示组成的经典方式。 然而,现在通常不建议使用它,因为馅饼部分的面积有时会变得误导。 因此,如果您要使用饼图,强烈建议明确记下饼图每个部分的百分比或数字。

 
 
  1. # Import

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


  3. # Prepare Data

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


  5. # Make the plot with pandas

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

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

  8. plt.ylabel("")

  9. plt.show()

640?wx_fmt=png

图10-1

640?wx_fmt=png

图10-2

六、变化 (Change)

11. 时间序列图 (Time Series Plot)

时间序列图用于显示给定度量随时间变化的方式。 在这里,您可以看到 1949年 至 1969年间航空客运量的变化情况。

 
 
  1. # Import Data

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


  3. # Draw Plot

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

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


  6. # Decoration

  7. plt.ylim(50, 750)

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

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

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

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

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

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


  14. # Remove borders

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

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

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

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

  19. plt.show()

640?wx_fmt=png

图11

12. 带波峰波谷标记的时序图 (Time Series with Peaks and Troughs Annotated)

下面的时间序列绘制了所有峰值和低谷,并注释了所选特殊事件的发生。

640?wx_fmt=png

图12

七、分组 (Groups)

13. 树状图 (Dendrogram)

树形图基于给定的距离度量将相似的点组合在一起,并基于点的相似性将它们组织在树状链接中。

 
 
  1. import scipy.cluster.hierarchy as shc


  2. # Import Data

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


  4. # Plot

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

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

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

  8. plt.xticks(fontsize=12)

  9. plt.show()

640?wx_fmt=png

图13

14. 簇状图 (Cluster Plot)

簇状图 (Cluster Plot)可用于划分属于同一群集的点。 下面是根据USArrests数据集将美国各州分为5组的代表性示例。 此图使用“谋杀”和“攻击”列作为X和Y轴。 或者,您可以将第一个到主要组件用作X轴和Y轴。

 
 
  1. from sklearn.cluster import AgglomerativeClustering

  2. from scipy.spatial import ConvexHull


  3. # Import Data

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


  5. # Agglomerative Clustering

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

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


  8. # Plot

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

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


  11. # Encircle

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

  13.    if not ax: ax=plt.gca()

  14.    p = np.c_[x,y]

  15.    hull = ConvexHull(p)

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

  17.    ax.add_patch(poly)


  18. # Draw polygon surrounding vertices    

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

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

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

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

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


  24. # Decorations

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

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

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

  28. plt.show()

640?wx_fmt=png

图14


以上 14 种可视化图表都可以通过 Python 来实现,甚至还可以完成更多类型的,包含 Matplotlib、Seaborn、Plotnine、Plotly 等。数据可视化是数据分析和机器学习的重要环节,比如数据清洗、特征工程、机器学习、数据分析(特别是报告)、评估等环节都会用到“数据可视化”技术。


扫码特价订阅

用 Python 搞定数据可视化

640?wx_fmt=jpeg


原文: 

Top 50 matplotlib Visualizations – The Master Plots (with full python code)

https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/


点击阅读原文,用 Python 轻松搞定数据可视化

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值