Python 小提琴图

Python ViolinPlots

我目前正在尝试用 this data set 制作小提琴情节。

我希望 x 轴是第一列(时间),总秒数。小提琴的左半部分是 AskBidAvg,而右半部分是 GrpAvg 是否有与使用 Hue 不同的方法,因为从示例中我看到它只需要一个具有 2 个唯一值的列。然而,我们在那里有许多不同的价值观。这是导致问题的原因。我们使用 1 分钟的增量,这是我根据总秒数 () 计算得出的。在 seaborn 或 matplotlib 中。 我当前使用的代码是:

sns.violinplot(x="Time",hue=["AskBidAvg", "GrpAvg"] ,inner ="quartiles" , linewidth= 1,split=True , data=df )

但是,它会抛出色调不能超过2个值的错误。

为了绘制您想要的图形,您需要对数据进行一些转换。

你有时间列 - 那个没问题你的第二列应该包含 y 值(它将包含所有数值)然后应该有另一列告诉你它是 AskBidAvg 还是 GrpAvg

    Time    variable    value
0   18000   AskBidAvg   -0.000019
1   18000   AskBidAvg   -0.000024
2   18000   AskBidAvg   0.000019
...     ...     ...     ...
76  18004   GrpAvg  -0.000019
77  18005   GrpAvg  -0.000005
78  18005   GrpAvg  -0.000012
79  18005   GrpAvg  0.000002

Pandas 有一个很好的功能可以为你做这件事。

import pandas as pd
df = pd.read_csv("/Users/james.natale/Downloads/yourdata.csv",index_col=False,header=0)
df = pd.melt(df, id_vars=['Time'], value_vars=['AskBidAvg', 'GrpAvg'])

import seaborn as sns
sns.set(style="whitegrid", palette="pastel", color_codes=True)

# Draw a nested violinplot and split the violins for easier comparison
sns.violinplot(x=df['Time'], y=df['value'], hue=df['variable'], split=True,
               inner="quart")
sns.despine(left=True)