【发布时间】:2020-12-07 15:17:41
【问题描述】:
我想从 3D 数据框中绘制线条,第三维是列索引中的额外级别。但我无法以适当的格式处理数据或适当地调用绘图函数。我正在寻找的是一个情节,其中许多系列被绘制在由外列索引排列的子图中。让我用一些随机数据来说明。
import numpy as np
import pandas as pd
n_points_per_series = 6
n_series_per_feature = 5
n_features = 4
shape = (n_points_per_series, n_features, n_series_per_feature)
data = np.random.randn(*shape).reshape(n_points_per_series, -1)
points = range(n_points_per_series)
features = [chr(ord('a') + i) for i in range(n_features)]
series = [f'S{i}' for i in range(n_series_per_feature)]
index = pd.Index(points, name='point')
columns = pd.MultiIndex.from_product((features, series)).rename(['feature', 'series'])
data = pd.DataFrame(data, index=index, columns=columns)
因此,对于这个特定的数据框,应该生成 4 个子图 (n_features),每个子图包含 5 个 (n_series_per_feature) 系列和 6 个数据点。由于该方法在索引方向上绘制线条并且可以为每一列生成子图,因此我尝试了一些变化:
data.plot()
data.plot(subplots=True)
data.stack().plot()
data.stack().plot(subplots=True)
它们都不起作用。要么生成了太多没有子图的线,要么为每条线单独制作一个子图,或者在沿索引的堆叠值连接到一个长系列之后。而且我认为x 和y 参数在这里不可用,因为将索引转换为列并在x 中使用它只会在整个地方产生一条长线:
data.stack().reset_index().set_index('series').plot(x='point', y=features)
根据我的经验,这类东西在 Pandas 中应该很简单,但我不知所措。这种次情节安排如何实现?如果不是单个函数调用,有没有比在 matplotlib 中生成子图并为手动绘制系列索引更方便的方法?
【问题讨论】:
-
您在寻找什么样的布局?
-
没有。您的示例数据框的预期绘图布局是什么?以及 N x M 轴网格,每个轴都有 P 系列? N、M 和 P 是什么?
-
根据其文档字符串
DataFrame.plot有一个layout参数