当前位置:   article > 正文

25个常用Matplotlib图的Python代码(二):边缘直方图、边缘箱型图、相关图、矩阵图、发散型条形图_matplotlib矩阵图

matplotlib矩阵图

1.边缘直方图

边缘直方图具有沿X和Y轴变量的直方图。这用于可视化X和Y之间的关系以及单独的X和Y的单变量分布。该图如果经常用于探索性数据分析(EDA)。

  1. # Import Data
  2. df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/mpg_ggplot2.csv")
  3. # Create Fig and gridspec
  4. fig = plt.figure(figsize=(16, 10), dpi= 80)
  5. grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)
  6. # Define the axes
  7. ax_main = fig.add_subplot(grid[:-1, :-1])
  8. ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])
  9. ax_bottom = fig.add_subplot(grid[-1, 0:-1], xticklabels=[], yticklabels=[])
  10. # Scatterplot on main ax
  11. ax_main.scatter('displ', 'hwy', s=df.cty*4, c=df.manufacturer.astype('category').cat.codes, alpha=.9, data=df, cmap="tab10", edgecolors='gray', linewidths=.5)
  12. # histogram on the right
  13. ax_bottom.hist(df.displ, 40, histtype='stepfilled', orientation='vertical', color='deeppink')
  14. ax_bottom.invert_yaxis()
  15. # histogram in the bottom
  16. ax_right.hist(df.hwy, 40, histtype='stepfilled', orientation='horizontal', color='deeppink')
  17. # Decorations
  18. ax_main.set(title='Scatterplot with Histograms
  19. displ vs hwy', xlabel='displ', ylabel='hwy')
  20. ax_main.title.set_fontsize(20)
  21. for item in ([ax_main.xaxis.label, ax_main.yaxis.label] + ax_main.get_xticklabels() + ax_main.get_yticklabels()):
  22. item.set_fontsize(14)
  23. xlabels = ax_main.get_xticks().tolist()
  24. ax_main.set_xticklabels(xlabels)
  25. plt.show()

7.边缘箱型图 

边缘箱图与边缘直方图具有相似的用途。然而,箱线图有助于精确定位X和Y的中位数,第25和第75百分位数。

  1. # Import Data
  2. df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/mpg_ggplot2.csv")
  3. # Create Fig and gridspec
  4. fig = plt.figure(figsize=(16, 10), dpi= 80)
  5. grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)
  6. # Define the axes
  7. ax_main = fig.add_subplot(grid[:-1, :-1])
  8. ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])
  9. ax_bottom = fig.add_subplot(grid[-1, 0:-1], xticklabels=[], yticklabels=[])
  10. # Scatterplot on main ax
  11. ax_main.scatter('displ', 'hwy', s=df.cty*5, c=df.manufacturer.astype('category').cat.codes, alpha=.9, data=df, cmap="Set1", edgecolors='black', linewidths=.5)
  12. # Add a graph in each part
  13. sns.boxplot(df.hwy, ax=ax_right, orient="v")
  14. sns.boxplot(df.displ, ax=ax_bottom, orient="h")
  15. # Decorations ------------------
  16. # Remove x axis name for the boxplot
  17. ax_bottom.set(xlabel='')
  18. ax_right.set(ylabel='')
  19. # Main Title, Xlabel and YLabel
  20. ax_main.set(title='Scatterplot with Histograms
  21. displ vs hwy', xlabel='displ', ylabel='hwy')
  22. # Set font size of different components
  23. ax_main.title.set_fontsize(20)
  24. for item in ([ax_main.xaxis.label, ax_main.yaxis.label] + ax_main.get_xticklabels() + ax_main.get_yticklabels()):
  25. item.set_fontsize(14)
  26. plt.show()

3.相关图

 Correlogram用于直观地查看给定数据帧(或2D数组)中所有可能的数值变量对之间的相关度量。

  1. # Import Dataset
  2. df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")
  3. # Plot
  4. plt.figure(figsize=(12,10), dpi= 80)
  5. sns.heatmap(df.corr(), xticklabels=df.corr().columns, yticklabels=df.corr().columns, cmap='RdYlGn', center=0, annot=True)
  6. # Decorations
  7. plt.title('Correlogram of mtcars', fontsize=22)
  8. plt.xticks(fontsize=12)
  9. plt.yticks(fontsize=12)
  10. plt.show()

4.矩阵图 

成对图是探索性分析中的最爱,以理解所有可能的数字变量对之间的关系。它是双变量分析的必备工具。

  1. # Load Dataset
  2. df = sns.load_dataset('iris')
  3. # Plot
  4. plt.figure(figsize=(10,8), dpi= 80)
  5. sns.pairplot(df, kind="scatter", hue="species", plot_kws=dict(s=80, edgecolor="white", linewidth=2.5))
  6. plt.show()

  1. # Load Dataset
  2. df = sns.load_dataset('iris')
  3. # Plot
  4. plt.figure(figsize=(10,8), dpi= 80)
  5. sns.pairplot(df, kind="reg", hue="species")
  6. plt.show()

 

 5.发散型条形图

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

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

 

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号