Matplotlib Seaborn 循环绘制图形

Matplotlib Seaborn 循环绘制图形

在数据分析的过程中,图形化展示数据是非常重要的一环。Matplotlib和Seaborn是Python绘制数据可视化的两大利器。本文将介绍如何使用循环在Matplotlib和Seaborn中快速生成多个相似的图形。

阅读更多:Matplotlib 教程

准备数据

为了方便演示,我们将以Iris数据集作为例子。首先,我们需要导入必要的库和数据集:

import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset('iris')
Python

Iris数据集共有150条记录,包含了三种不同花的观测数据,每种花各有50条记录,每条记录包含了4个特征:花萼长度、花萼宽度、花瓣长度和花瓣宽度。

循环绘制散点图

假设我们需要绘制每种花的花萼长度和花萼宽度的散点图。我们可以使用循环在Matplotlib中绘制出这三张图:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))

for i, species in enumerate(iris.species.unique()):
    ax = axes[i]
    data = iris.query('species == @species')
    ax.scatter(data.sepal_length, data.sepal_width)

    ax.set_xlabel('Sepal Length')
    ax.set_ylabel('Sepal Width')
    ax.set_title(species)

plt.show()
Python

上述代码中,我们首先通过unique()函数找到了三种不同的花,然后在循环中分别取出每种花的数据,使用scatter()函数绘制出散点图,最后设置横纵坐标轴标签和标题,生成了三张散点图。

如果要使用Seaborn,则可以使用下面的代码:

g = sns.FacetGrid(iris, col='species', hue='species', height=4)
g.map(plt.scatter, 'sepal_length', 'sepal_width')

g.set_axis_labels('Sepal Length', 'Sepal Width')
g.set_titles("{col_name}")
g.set_xticklabels(rotation=45)

sns.despine()
plt.show()
Python

使用Seaborn,我们可以通过FacetGrid对象在一个画布上画多个子图。该对象需要两个参数:数据集和按照哪个变量分组。然后,我们使用map()函数指定绘制函数和绘制的变量,并在其它属性中设置横纵坐标轴标签和标题,生成了三张散点图。

循环绘制直方图

假设我们需要绘制每种花的花萼长度的直方图。我们可以使用循环在Matplotlib中绘制出这三张图:

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))

for i, species in enumerate(iris.species.unique()):
    ax = axes[i]
    data = iris.query('species == @species')
    ax.hist(data.sepal_length, bins=10)

    ax.set_xlabel('Sepal Length')
    ax.set_ylabel('Frequency')
    ax.set_title(species)

plt.show()
Python

上述代码中,我们首先通过unique()函数找到了三种不同的花,然后在循环中分别取出每种花的数据,使用hist()函数绘制出直方图,最后设置横纵坐标轴标签和标题,生成了三张直方图。

如果要使用Seaborn,则可以使用下面的代码:

g = sns.FacetGrid(iris, col='species', height=4)
g.map(sns.distplot, 'sepal_length')

g.set_axis_labels('Sepal Length', 'Density')
g.set_titles("{col_name}")
g.set_xticklabels(rotation=45)

sns.despine()
plt.show()
Python

使用Seaborn,我们同样可以通过FacetGrid对象在一个画布上画多个子图。该对象需要两个参数:数据集和按照哪个变量分组。然后,我们使用map()函数指定绘制函数和绘制的变量,并在其它属性中设置横纵坐标轴标签和标题,生成了三张直方图。

循环绘制箱线图

假设我们需要绘制每种花的花萼长度和花瓣长度的箱线图。我们可以使用循环在Matplotlib中绘制出这两张图:

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))

for i, feature in enumerate(['sepal_length', 'petal_length']):
    ax = axes[i]
    sns.boxplot(x='species', y=feature, data=iris, ax=ax)

    ax.set_xlabel('Species')
    ax.set_ylabel(feature.capitalize())

plt.show()
Python

上述代码中,我们在循环中分别取出sepal_lengthpetal_length两个特征的数据,使用boxplot()函数绘制出箱线图,最后设置横纵坐标轴标签,生成了两张箱线图。

如果要使用Seaborn,则可以使用下面的代码:

g = sns.FacetGrid(iris, col='species', height=4, aspect=0.8)
g.map(sns.boxplot, 'species', 'sepal_length')

g.set_axis_labels('', 'Sepal Length')
g.set_titles("{col_name}")
g.set_xticklabels(rotation=45)

sns.despine()
plt.show()

g = sns.FacetGrid(iris, col='species', height=4, aspect=0.8)
g.map(sns.boxplot, 'species', 'petal_length')

g.set_axis_labels('', 'Petal Length')
g.set_titles("{col_name}")
g.set_xticklabels(rotation=45)

sns.despine()
plt.show()
Python

使用Seaborn,我们同样可以通过FacetGrid对象在一个画布上画多个子图。该对象需要两个参数:数据集和按照哪个变量分组。然后,我们使用map()函数指定绘制函数和绘制的变量,并在其它属性中设置横纵坐标轴标签和标题,生成了两张箱线图。

总结

在Python中,使用循环快速生成多个相似的图形是非常常见的需求。本文介绍了如何在Matplotlib和Seaborn中使用循环绘制散点图、直方图和箱线图。通过这些示例,相信读者已经掌握了如何在Python中快速生成多个相似的图形。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册