【问题标题】:Applying and plotting data with multi-label classification应用和绘制具有多标签分类的数据
【发布时间】:2021-02-16 13:03:07
【问题描述】:

我想从可以属于多个类别的 pandas 数据帧创建(例如)小提琴图,最好是在一个图中。但是不知道该怎么做——有什么建议吗?非常感谢!

显示单独图的简单示例。这里,x 是主要分组变量,y 是要分组的数据,z 定义成员资格/类别。为简单起见,我只是将z 随机设置为[0,1,2] 的整数。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# dummy data
np.random.seed(12345)
x = np.random.randint(1,6,1000)
y = np.random.randn(1000)
z = np.random.randint(0,3,1000)
df = pd.DataFrame(data=np.array([x,y,z]).T,columns=['x','y','z'])

所有数据(用于验证?):

sns.violinplot(x='x',y='y',data=df)
plt.title('all data')

Violin plot of all data regardless of Z

个别地块:

fig,ax = plt.subplots(nrows=3,ncols=1,sharex=True)

sns.violinplot(x='x',y='y',data=df.loc[df['z']<=0],ax=ax[0])
ax[0].set_title('z <= 0')

sns.violinplot(x='x',y='y',data=df.loc[df['z']<=1],ax=ax[1])
ax[1].set_title('z <= 1')

sns.violinplot(x='x',y='y',data=df.loc[df['z']<=2],ax=ax[2])
ax[2].set_title('z <= 2')
plt.tight_layout();

3 violin plots of data with z<=[0,1,2] respectively

我想要的是一个如下所示的图,除了“z”使用上述图的分组:

plt.figure()
sns.violinplot(x='x',y='y',data=df,hue='z');

Violin plot using 'hue' where only data with z==[0,1,2] is grouped for each color

【问题讨论】:

  • 你能澄清一下“除了'z'使用上述情节的分组”是什么意思吗?你想让你的小提琴看起来像sns.kdeplot(..., multiple='layer')吗?无论如何,以适当的数量缩放所有内容是一个棘手的问题。一个想法可能是创建一个充满sns.kdeplot(..., multiple='layer')ridge plot

标签: python pandas seaborn


【解决方案1】:

您可以通过创建一个新的数据框来做到这一点,其中包含您希望通过色调显示的z 的选择:

import numpy as np     # v 1.19.2
import pandas as pd    # v 1.1.3
import seaborn as sns  # v 0.11.0

# Create sample dataset
np.random.seed(12345)
x = np.random.randint(1,6,1000)
y = np.random.randn(1000)
z = np.random.randint(0,3,1000)
df = pd.DataFrame(data=np.array([x,y,z]).T,columns=['x','y','z'])

# Create new dataframe containing the selections of the 'z' variable
df0 = df.loc[df['z']<=0]
df1 = df.loc[df['z']<=1]
df2 = df.loc[df['z']<=2]
dfnew = pd.concat([df0, df1, df2], keys=['z <= 0', 'z <= 1', 'z <= 2'])
dfnew.reset_index(inplace=True)
dfnew.drop(columns='level_1', inplace=True)
dfnew.rename(columns={'level_0':'z selection'}, inplace=True)
dfnew.head()

#     z selection    x          y    z
#  0       z <= 0  3.0  -0.670121  0.0
#  1       z <= 0  3.0  -2.016201  0.0
#  2       z <= 0  2.0  -0.266742  0.0
#  3       z <= 0  2.0  -0.406730  0.0
#  4       z <= 0  2.0  -0.243281  0.0
ax = sns.violinplot(x='x', y='y', data=dfnew, hue='z selection')
ax.figure.set_size_inches(9, 6)

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 2020-07-17
    • 2019-07-14
    • 2020-12-01
    • 1970-01-01
    • 2019-10-12
    • 2018-03-07
    • 2021-07-17
    • 2020-10-24
    相关资源
    最近更新 更多