【问题标题】:Plot multiple lines in subplots在子图中绘制多条线
【发布时间】: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)

它们都不起作用。要么生成了太多没有子图的线,要么为每条线单独制作一个子图,或者在沿索引的堆叠值连接到一个长系列之后。而且我认为xy 参数在这里不可用,因为将索引转换为列并在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 参数

标签: python pandas plot


【解决方案1】:

如果您可以使用seaborn,它可用于从数据框列生成子图,然后可以将其他列的图映射到该子图上。使用与您相同的设置,我会尝试以下方式:

import seaborn as sns

# Completely stack the data frame
df = data \
    .stack() \
    .stack() \
    .rename("value") \
    .reset_index()

# Create grid and map line plots
g = sns.FacetGrid(df, col="feature", col_wrap=2, hue="series")
g.map_dataframe(sns.lineplot, x="point", y="value")
g.add_legend()

输出:

【讨论】:

  • 你可以使用g.map,你不需要g.map_dataframe
  • @PaulH 似乎需要map_dataframemap 产生一个ValueError: Could not interpret input 'point'
  • @Felix 很高兴这有帮助。仅供参考,我进行了更多编辑以显示轴标签和图例。
  • 如果你想让你的图更漂亮,你可以将任何格式参数传递给g.map_dataframe(),这将适用于matplotlib.axes.Axes.plot()
  • @CanisLupusOccidentalis 非常有帮助,谢谢!非常感激。如果您不介意,我编辑了答案以压缩信息并进行更多解释。
猜你喜欢
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-02
相关资源
最近更新 更多