这是一个旧问题的新答案,因为在seaborn
和pandas
是通过版本更新进行的一些更改。由于这种变化,Rutger 的答案不再起作用。
最重要的变化是从seaborn==v0.5.x
到seaborn==v0.6.0
。我引用日志:
变化可能是最具破坏性的boxplot()
。violinplot()
这两个函数在它们可以接受的数据类型方面保持向后兼容性,但语法已更改为与其他 seaborn 函数更相似。这些函数现在使用x
和/或y
参数调用,这些参数要么是数据向量,要么是传递给新数据参数的长格式 DataFrame 中的变量名称。
现在让我们来看看这些例子:
# preamble
import pandas as pd # version 1.1.4
import seaborn as sns # version 0.11.0
sns.set_theme()
示例 1:简单箱线图
df = pd.DataFrame([[2, 1] ,[4, 2],[5, 1],
[10, 2],[9, 2],[3, 1]
], columns=['a', 'b'])
#Plotting by seaborn with x and y as parameter
sns.boxplot(x='b', y='a', data=df)

示例 2:带石斑鱼的箱线图
df = pd.DataFrame([[2, 5, 1], [4, 9, 2],[5, 3, 1],
[10, 6, 2],[9, 7, 2],[3, 11, 1]
], columns=['a', 'b', 'grouper'])
# usinge pandas melt
df_long = pd.melt(df, "grouper", var_name='a', value_name='b')
# join two columns together
df_long['a'] = df_long['a'].astype(str) + df_long['grouper'].astype(str)
sns.boxplot(x='a', y='b', data=df_long)

示例 3:重新排列要传递的 DataFrame 是直接传递给 seaborn
def df_rename_by_group(data:pd.DataFrame, col:str)->pd.DataFrame:
'''This function takes a DataFrame, groups by one column and returns
a new DataFrame where the old columnnames are extended by the group item.
'''
grouper = df.groupby(col)
max_length_of_group = max([len(values) for item, values in grouper.indices.items()])
_df = pd.DataFrame(index=range(max_length_of_group))
for i in grouper.groups.keys():
helper = grouper.get_group(i).drop(col, axis=1).add_suffix(str(i))
helper.reset_index(drop=True, inplace=True)
_df = _df.join(helper)
return _df
df = pd.DataFrame([[2, 5, 1], [4, 9, 2],[5, 3, 1],
[10, 6, 2],[9, 7, 2],[3, 11, 1]
], columns=['a', 'b', 'grouper'])
df_new = df_rename_by_group(data=df, col='grouper')
sns.boxplot(data=df_new)

我真的希望这个答案有助于避免一些混乱。