python - 如何从 scatter_matrix 获取数据数组

标签 python pandas matplotlib

我正在使用pandasscatter_matrix,我想知道如何在每个散点矩阵上绘制二维数组?另外,如何识别输出的哪个 AxesSubplot 是输出图上的哪个矩阵?

最佳答案

scatter_matrixpandas 的一个便利函数,来自 pandas.plotting 子模块。而the documentation is scarce (docstring 只是更有帮助一点),这个例子让我们很容易理解它是如何工作的。考虑文档中的示例:

import numpy as np # only needed for the example input
import pandas as pd
from pandas.plotting import scatter_matrix

df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
axs = scatter_matrix(df, alpha=0.2, figsize=(6,6), diagonal='kde')
axs[0,0].get_figure().show() # or import and call matplotlib.pyplot.show

example scatter_matrix output

注意底部和左侧轴上的标签:这些标签指示输入数据帧的哪些列在给定的行/列中相互绘制。在第一列图中,x 轴对应于 df.a,在第二行图中,y 轴对应于 df.b 等等(在对角线上绘制各列的密度或直方图)。因此,绘图矩阵中的转置元素对应于 x 和 y 数据的交换,即绘图相对于 x=y 线的反射(reflect)。如果您仔细观察上图,您会发现确实如此。

换句话说,您不需要计算各个轴的数据,因为您可以直接控制输入数据。在非对角轴 axs[i,j] 中,x 数据由 df[df.columns[j]] 给出,y 数据由 给出>df[df.columns[i]]。下面是一个快速拼凑,可以帮助可视化顺序:

axs = scatter_matrix(df, alpha=0.2, figsize=(6,6), diagonal='kde')
for i in range(axs.shape[0]):
    for j in range(axs.shape[1]):
        if i == j:
            continue
        axs[i,j].set_title('x: {}, y: {}'.format(df.columns[j],df.columns[i]),
                           position=(0.5,0.5))

example scatter_matrix output with annotations showing the x and y sources for each off-diagonal plot

因此,虽然可以深入了解每个 AxesSubplot 对象的内部并从中提取数据,但使用 df 的相应列要简单得多> 直接。一个异常(exception)是对角线:在核密度图的情况下(假设 diagonal='kde' 关键字已传递给 scatter_matrix),您无法直接访问基础数据。在这种情况下,您可以从对角线 AxesSubplots 中提取线条:

import matplotlib.pyplot as plt
index = 0
xdat,ydat = axs[index,index].get_lines()[0].get_data() # example for diagonal [0,0]
plt.figure()
plt.plot(xdat,ydat,'-')
plt.xlabel(df.columns[index])
plt.ylabel('density')

关于python - 如何从 scatter_matrix 获取数据数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967734/

相关文章:

python - 如何向该数据框添加趋势线 (Python)

Python:将参数卡住到类 __init__ 函数中

python - Pandas groupby 自定义组

python - 存储 NumPy 行和列标题

python - 如何在 Pandas 中选择缺失数据超过一定数量的行/列?

python - Pandas 如何在数据帧列中过滤具有特定范围数字的数据帧

python - 通过 Seaborn 双绘图 X 轴

Python - pcolor 的 Pick_Event 获取 pandas 列和索引值

python - 为什么在 Python 中处理排序的数组并不比处理未排序的数组快?

Python 问题 :Unable to find vcvarsall. bat