Pandas中连续数据的平行坐标图

4 投票
1 回答
7297 浏览
提问于 2025-04-18 05:51

pandas库里的parallel_coordinates函数非常好用:

import pandas
import matplotlib.pyplot as plt
from pandas.tools.plotting import parallel_coordinates
sampdata = read_csv('/usr/local/lib/python3.3/dist-packages/pandas/tests/data/iris.csv')
parallel_coordinates(sampdata, 'Name')

enter image description here

但是当你处理连续数据时,它的表现可能和你想的不太一样:

mypos = np.random.randint(10, size=(100, 2))
mydata = DataFrame(mypos, columns=['x', 'y'])
myres = np.random.rand(100, 1)
mydata['res'] = myres
parallel_coordinates(mydata, 'res')

enter image description here

我希望线条的颜色能够反映连续变量的大小,比如从白色到黑色的渐变,最好还能有一些透明度(alpha值),旁边再加一个颜色条。

1 个回答

10

我今天遇到了完全一样的问题。我的解决办法是复制pandas中的parallel_coordinates函数,并根据我的特殊需求进行了调整。因为我觉得这对其他人也可能有用,所以我把我的实现分享出来:

def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
                     use_columns=False, xticks=None, colormap=None,
                     **kwds):
    import matplotlib.pyplot as plt
    import matplotlib as mpl

    n = len(frame)
    class_col = frame[class_column]
    class_min = np.amin(class_col)
    class_max = np.amax(class_col)

    if cols is None:
        df = frame.drop(class_column, axis=1)
    else:
        df = frame[cols]

    used_legends = set([])

    ncols = len(df.columns)

    # determine values to use for xticks
    if use_columns is True:
        if not np.all(np.isreal(list(df.columns))):
            raise ValueError('Columns must be numeric to be used as xticks')
        x = df.columns
    elif xticks is not None:
        if not np.all(np.isreal(xticks)):
            raise ValueError('xticks specified must be numeric')
        elif len(xticks) != ncols:
            raise ValueError('Length of xticks must match number of columns')
        x = xticks
    else:
        x = range(ncols)

    fig = plt.figure()
    ax = plt.gca()

    Colorm = plt.get_cmap(colormap)

    for i in range(n):
        y = df.iloc[i].values
        kls = class_col.iat[i]
        ax.plot(x, y, color=Colorm((kls - class_min)/(class_max-class_min)), **kwds)

    for i in x:
        ax.axvline(i, linewidth=1, color='black')

    ax.set_xticks(x)
    ax.set_xticklabels(df.columns)
    ax.set_xlim(x[0], x[-1])
    ax.legend(loc='upper right')
    ax.grid()

    bounds = np.linspace(class_min,class_max,10)
    cax,_ = mpl.colorbar.make_axes(ax)
    cb = mpl.colorbar.ColorbarBase(cax, cmap=Colorm, spacing='proportional', ticks=bounds, boundaries=bounds, format='%.2f')

    return fig

我不确定这个方法是否适用于pandas原始函数提供的所有选项。但对于你的例子,它的效果大概是这样的:

parallel_coordinates(mydata, 'res', colormap="binary")

问题中的示例

你可以通过修改之前函数中的这一行来添加透明度:

ax.plot(x, y, color=Colorm((kls - class_min)/(class_max-class_min)), alpha=(kls - class_min)/(class_max-class_min), **kwds)

对于pandas的原始示例,可以去掉名称,并使用最后一列作为数值:

sampdata = read_csv('iris_modified.csv')
parallel_coordinates(sampdata, 'Value')

pandas文档中的示例

希望这能帮到你!

Christophe

撰写回答