带直方图的散点图

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

本实验将指导你如何使用Matplotlib创建带有直方图的散点图。带有直方图的散点图是可视化两个变量的分布及其关系的好方法。散点图展示了两个变量之间的关系,而直方图则分别显示了每个变量的分布。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问Jupyter Notebook进行练习。

有时,你可能需要等待几秒钟让Jupyter Notebook完成加载。由于Jupyter Notebook的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向Labby提问。课程结束后提供反馈,我们将立即为你解决问题。

导入库

在开始之前,我们需要导入必要的库。在本实验中,我们将使用Matplotlib和NumPy。

import matplotlib.pyplot as plt
import numpy as np

生成随机数据

我们将生成一些随机数据,用于散点图和直方图。

## Fixing random state for reproducibility
np.random.seed(19680801)

## Generate random data
x = np.random.randn(1000)
y = np.random.randn(1000)

定义scatter_hist函数

我们需要定义scatter_hist函数,它接受x和y数据,以及三个坐标轴,一个用于散点图的主坐标轴,和两个边缘坐标轴。然后它将在所提供的坐标轴内创建散点图和直方图。

def scatter_hist(x, y, ax, ax_histx, ax_histy):
    ## Remove labels from the histograms
    ax_histx.tick_params(axis="x", labelbottom=False)
    ax_histy.tick_params(axis="y", labelleft=False)

    ## Create the scatter plot
    ax.scatter(x, y)

    ## Determine nice limits by hand
    binwidth = 0.25
    xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
    lim = (int(xymax/binwidth) + 1) * binwidth

    bins = np.arange(-lim, lim + binwidth, binwidth)
    ax_histx.hist(x, bins=bins)
    ax_histy.hist(y, bins=bins, orientation='horizontal')

使用网格布局定义坐标轴位置

我们现在将定义一个具有不等宽高比的gridspec,以实现所需的布局。我们还将创建坐标轴并将它们传递给scatter_hist函数。

## Start with a square Figure.
fig = plt.figure(figsize=(6, 6))
## Add a gridspec with two rows and two columns and a ratio of 1 to 4 between
## the size of the marginal axes and the main axes in both directions.
## Also adjust the subplot parameters for a square plot.
gs = fig.add_gridspec(2, 2,  width_ratios=(4, 1), height_ratios=(1, 4),
                      left=0.1, right=0.9, bottom=0.1, top=0.9,
                      wspace=0.05, hspace=0.05)
## Create the Axes.
ax = fig.add_subplot(gs[1, 0])
ax_histx = fig.add_subplot(gs[0, 0], sharex=ax)
ax_histy = fig.add_subplot(gs[1, 1], sharey=ax)
## Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)

使用inset_axes定义坐标轴位置

我们也可以使用inset_axes将边缘坐标轴定位在主坐标轴之外。这样做的好处是主坐标轴的宽高比可以固定,并且边缘坐标轴将始终相对于坐标轴的位置绘制。

## Create a Figure, which doesn't have to be square.
fig = plt.figure(layout='constrained')
## Create the main axes, leaving 25% of the figure space at the top and on the right to position marginals.
ax = fig.add_gridspec(top=0.75, right=0.75).subplots()
## The main axes' aspect can be fixed.
ax.set(aspect=1)
## Create marginal axes, which have 25% of the size of the main axes.
## Note that the inset axes are positioned *outside* (on the right and the top) of the main axes,
## by specifying axes coordinates greater than 1.
## Axes coordinates less than 0 would likewise specify positions on the left and the bottom of the main axes.
ax_histx = ax.inset_axes([0, 1.05, 1, 0.25], sharex=ax)
ax_histy = ax.inset_axes([1.05, 0, 0.25, 1], sharey=ax)
## Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)

显示图表

最后,我们可以使用plt.show()来显示图表。

plt.show()

总结

在本实验中,我们学习了如何使用Matplotlib创建带有直方图的散点图。我们定义了scatter_hist函数,生成了随机数据,使用网格布局(gridspec)和内嵌坐标轴(inset_axes)定义了坐标轴位置,并显示了图表。带有直方图的散点图是可视化两个变量的分布及其关系的好方法。