python - Pandas scatter_matrix 中的类标签

标签 python matplotlib pandas scatter-plot

这个问题之前有人问过,Multiple data in scatter matrix ,但没有收到答复。

我想制作一个散点矩阵,类似于 in the pandas docs , 但不同类别有不同颜色的标记。例如,我希望根据其中一列(或单独的列表)的值,某些点显示为绿色,其他点显示为蓝色。

这是一个使用 Iris 数据集的示例。点的颜色代表鸢尾的种类——Setosa、Versicolor 或 Virginica。

iris scattermatrix with class labels

pandas(或 matplotlib)有办法制作这样的图表吗?

最佳答案

更新:此功能现已包含在最新版本的 Seaborn 中。 Here's an example .

以下是我的权宜之计:

def factor_scatter_matrix(df, factor, palette=None):
    '''Create a scatter matrix of the variables in df, with differently colored
    points depending on the value of df[factor].
    inputs:
        df: pandas.DataFrame containing the columns to be plotted, as well 
            as factor.
        factor: string or pandas.Series. The column indicating which group 
            each row belongs to.
        palette: A list of hex codes, at least as long as the number of groups.
            If omitted, a predefined palette will be used, but it only includes
            9 groups.
    '''
    import matplotlib.colors
    import numpy as np
    from pandas.tools.plotting import scatter_matrix
    from scipy.stats import gaussian_kde

    if isinstance(factor, basestring):
        factor_name = factor #save off the name
        factor = df[factor] #extract column
        df = df.drop(factor_name,axis=1) # remove from df, so it 
        # doesn't get a row and col in the plot.

    classes = list(set(factor))

    if palette is None:
        palette = ['#e41a1c', '#377eb8', '#4eae4b', 
                   '#994fa1', '#ff8101', '#fdfc33', 
                   '#a8572c', '#f482be', '#999999']

    color_map = dict(zip(classes,palette))

    if len(classes) > len(palette):
        raise ValueError('''Too many groups for the number of colors provided.
We only have {} colors in the palette, but you have {}
groups.'''.format(len(palette), len(classes)))

    colors = factor.apply(lambda group: color_map[group])
    axarr = scatter_matrix(df,figsize=(10,10),marker='o',c=colors,diagonal=None)


    for rc in xrange(len(df.columns)):
        for group in classes:
            y = df[factor == group].icol(rc).values
            gkde = gaussian_kde(y)
            ind = np.linspace(y.min(), y.max(), 1000)
            axarr[rc][rc].plot(ind, gkde.evaluate(ind),c=color_map[group])

    return axarr, color_map

例如,我们将使用与问题中相同的数据集,可用 here

>>> import pandas as pd
>>> iris = pd.read_csv('iris.csv')
>>> axarr, color_map = factor_scatter_matrix(iris,'Name')
>>> color_map
{'Iris-setosa': '#377eb8',
 'Iris-versicolor': '#4eae4b',
 'Iris-virginica': '#e41a1c'}

iris_scatter_matrix

希望对您有所帮助!

关于python - Pandas scatter_matrix 中的类标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943894/

相关文章:

尝试使用 cx_Freeze 进行编译时 Python 崩溃

python - Matplotlib savefig() over multiple graphs keeps saving the same graph

python - Pandas 对开始日期之后发生的列中的数据求和

python - 在 HDF5 中存储 Pandas 对象和常规 Python 对象

python - 根据另一个数据帧中的匹配 id 替换数据帧列值

python - 如何从 django 模型获取 datetime.date() 值?

python - 奥尔德林 Hello World 问题

python - 以半小时频率绘制 xtick 标签

python - 为什么我的颜色条中有线条?

python - 当一个序列在 df 中的簇中时删除原始数据