给定 numpy ndarray 随时间变化的 Seaborn 小提琴图

Seaborn violin plot over time given numpy ndarray

我有一个随时间变化的分布,我想使用 seaborn 为每个时间步并排绘制小提琴图。我最初的尝试失败了,因为 violinplot 无法处理 y 参数的 np.ndarray

import numpy as np
import seaborn as sns

time = np.arange(0, 10)
samples = np.random.randn(10, 200)

ax = sns.violinplot(x=time, y=samples)  # Exception: Data must be 1-dimensional

seaborn documentation 有一个按分类变量分组的垂直小提琴图示例。但是,它使用长格式的 DataFrame。

我是否也需要将时间序列转换为 DataFrame?如果是这样,我该如何实现?

在 violin plot 文档中它说输入 x 和 y 参数不必是数据框,但它们有相同维度的限制。此外,您创建的变量 y 有 10 行和 200 列。这在绘制图形时是有害的,会导致尺寸问题。 我测试了一下,这段代码读取python文件没有问题。

import numpy as np
import seaborn as sns
import pandas as pd

time = np.arange(0, 200)
samples = np.random.randn(10, 200)

for sample in samples:
    ax = sns.violinplot(x=time, y=sample)

然后您可以使用此 link 对生成的图表进行分组: https://python-graph-gallery.com/199-matplotlib-style-sheets/

如果您想将数据转换为数据框,也是可以的。你只需要使用 pandas.

例子

import pandas as pd
x = [1,2,3,4]
df = pd.DataFrame(x)

仔细查看文档让我意识到完全省略 xy 参数会导致 data 参数以宽格式解释:

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt


samples = np.random.randn(20, 10)
ax = sns.violinplot(data=samples)
plt.show()