我用Python的Matplotlib库绘制25个超好看图表

您所在的位置:网站首页 图案怎么画好看 我用Python的Matplotlib库绘制25个超好看图表

我用Python的Matplotlib库绘制25个超好看图表

2024-07-15 03:56| 来源: 网络整理| 查看: 265

今天要分享给大家25个Matplotlib图的汇总, 在数据分析和可视化中非常有用,文章较长,可以码起来慢慢练手。

# !pip install brewer2mplimport numpy as npimport pandas as pdimport matplotlib as mplimport matplotlib.pyplot as pltimport seaborn as snsimport warnings; warnings.filterwarnings(action='once')large = 22; med = 16; small = 12params = {'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# Versionprint(mpl.__version__)  #> 3.0.0print(sns.__version__)  #> 0.9.0

1. 散点图

Scatteplot是用于研究两个变量之间关系的经典和基本图。如果数据中有多个组,则可能需要以不同颜色可视化每个组。在Matplotlib,你可以方便地使用。

# 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 Categoryplt.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, c=colors[i], label=str(category))# Decorationsplt.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()    

   2. 带边界的气泡图

有时,您希望在边界内显示一组点以强调其重要性。在此示例中,您将从应该被环绕的数据帧中获取记录,并将其传递给下面的代码中描述的记录。encircle()

from matplotlib import patchesfrom scipy.spatial import ConvexHullimport warnings; warnings.simplefilter('ignore')sns.set_style("white")# Step 1: Prepare Datamidwest = 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 categoryfig = 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', c=colors[i], label=str(category), edgecolors='black', linewidths=.5)# Step 3: Encircling# https://stackoverflow.com/questions/44575681/how-do-i-encircle-different-data-sets-in-scatter-plotdef 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)# Select data to be encircledmidwest_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: Decorationsplt.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()    

   3. 带线性回归最佳拟合线的散点图

如果你想了解两个变量如何相互改变,那么最合适的线就是要走的路。下图显示了数据中各组之间最佳拟合线的差异。要禁用分组并仅为整个数据集绘制一条最佳拟合线,请从下面的调用中删除该参数。

# Import Datadf = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/mpg_ggplot2.csv")df_select = df.loc[df.cyl.isin([4,8]), :]# Plotsns.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'))# Decorationsgridobj.set(xlim=(0.5, 7.5), ylim=(0, 50))plt.title("Scatterplot with line of best fit grouped by number of cylinders", fontsize=20)

每个回归线都在自己的列中

或者,您可以在其自己的列中显示每个组的最佳拟合线。你可以通过在里面设置参数来实现这一点。

# Import Datadf = 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 columnsns.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'))# Decorationsgridobj.set(xlim=(0.5, 7.5), ylim=(0, 50))plt.show()

   4. 抖动图

通常,多个数据点具有完全相同的X和Y值。结果,多个点相互绘制并隐藏。为避免这种情况,请稍微抖动点,以便您可以直观地看到它们。这很方便使用

# Import Datadf = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/mpg_ggplot2.csv")# Draw Stripplotfig, ax = plt.subplots(figsize=(16,10), dpi= 80)    sns.stripplot(df.cty, df.hwy, jitter=0.25, size=8, ax=ax, linewidth=.5)# Decorationsplt.title('Use jittered plots to avoid overlapping of points', fontsize=22)plt.show()

   5. 计数图

避免点重叠问题的另一个选择是增加点的大小,这取决于该点中有多少点。因此,点的大小越大,周围的点的集中度就越大。

# Import Datadf = 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 Stripplotfig, ax = plt.subplots(figsize=(16,10), dpi= 80)    sns.stripplot(df_counts.cty, df_counts.hwy, size=df_counts.counts*2, ax=ax)# Decorationsplt.title('Counts Plot - Size of circle is bigger as more points overlap', fontsize=22)plt.show()

   6. 边缘直方图

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

# Import Datadf = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/mpg_ggplot2.csv")# Create Fig and gridspecfig = plt.figure(figsize=(16, 10), dpi= 80)grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)# Define the axesax_main = fig.add_subplot(grid[:-1, :-1])ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])ax_bottom = fig.add_subplot(grid[-1, 0:-1], xticklabels=[], yticklabels=[])# Scatterplot on main axax_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)# histogram on the rightax_bottom.hist(df.displ, 40, histtype='stepfilled', orientation='vertical', color='deeppink')ax_bottom.invert_yaxis()# histogram in the bottomax_right.hist(df.hwy, 40, histtype='stepfilled', orientation='horizontal', color='deeppink')# Decorationsax_main.set(title='Scatterplot with Histograms  displ vs hwy', xlabel='displ', ylabel='hwy')ax_main.title.set_fontsize(20)for item in ([ax_main.xaxis.label, ax_main.yaxis.label] + ax_main.get_xticklabels() + ax_main.get_yticklabels()):    item.set_fontsize(14)xlabels = ax_main.get_xticks().tolist()ax_main.set_xticklabels(xlabels)plt.show()

   7.边缘箱形图

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

# Import Datadf = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/mpg_ggplot2.csv")# Create Fig and gridspecfig = plt.figure(figsize=(16, 10), dpi= 80)grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)# Define the axesax_main = fig.add_subplot(grid[:-1, :-1])ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])ax_bottom = fig.add_subplot(grid[-1, 0:-1], xticklabels=[], yticklabels=[])# Scatterplot on main axax_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)# Add a graph in each partsns.boxplot(df.hwy, ax=ax_right, orient="v")sns.boxplot(df.displ, ax=ax_bottom, orient="h")# Decorations ------------------# Remove x axis name for the boxplotax_bottom.set(xlabel='')ax_right.set(ylabel='')# Main Title, Xlabel and YLabelax_main.set(title='Scatterplot with Histograms  displ vs hwy', xlabel='displ', ylabel='hwy')# Set font size of different componentsax_main.title.set_fontsize(20)for item in ([ax_main.xaxis.label, ax_main.yaxis.label] + ax_main.get_xticklabels() + ax_main.get_yticklabels()):    item.set_fontsize(14)plt.show()

   8. 相关图

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

# Import Datasetdf = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")# Plotplt.figure(figsize=(12,10), dpi= 80)sns.heatmap(df.corr(), xticklabels=df.corr().columns, yticklabels=df.corr().columns, cmap='RdYlGn', center=0, annot=True)# Decorationsplt.title('Correlogram of mtcars', fontsize=22)plt.xticks(fontsize=12)plt.yticks(fontsize=12)plt.show()

   9. 矩阵图

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

# Load Datasetdf = sns.load_dataset('iris')# Plotplt.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()

# Load Datasetdf = sns.load_dataset('iris')# Plotplt.figure(figsize=(10,8), dpi= 80)sns.pairplot(df, kind="reg", hue="species")plt.show()

   10. 发散型条形图

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

# Prepare Datadf = 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 'size':20})'color':'red' if x 'size':20})'color':'white'})'size':20})'size':20})'horizontalalignment': 'center', 'verticalalignment': 'center_baseline'})'size':22})'size':22})'horizontalalignment': 'right', 'size':12})'size':22})'horizontalalignment': 'right'})'size':14})'size':14})'size':18, 'weight':700})'size':18, 'weight':700})'size':22})'size':22})group:col for group, col in zip(np.unique(df[groupby_var]).tolist(), colors[:len(vals)])})group:col for group, col in zip(np.unique(df[groupby_var]).tolist(), colors[:len(vals)])})'alpha':.7}, kde_kws={'linewidth':3})'alpha':.7}, kde_kws={'linewidth':3})'alpha':.7}, kde_kws={'linewidth':3})4:'tab:red', 5:'tab:green', 6:'tab:blue', 8:'tab:orange'}'size':12}, color='firebrick')'size':22})'horizontalalignment': 'right'}, alpha=0.7)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3