[英]Matplotlib: Plot countplot for two or more column on single plot
My dataFrame, df:我的数据帧,df:
Sno | Attribute_1 | Attribute_2 | Attribute_3
__________________________________________________
1 | option_1 | option_3 |option_2
2 | option_1 | option_1 |option_1
3 | option_2 | option_2 |option_2
4 | option_1 | option_1 |option_3
5 | option_3 | option_2 |option_2
6 | option_3 | option_3 |option_1
7 | option_1 | option_3 |option_2
Here Attribute_1, Attribute_2 and Attribute_3 contains categorical data - option_1 or option_2 or option_3 for each of the rows.这里 Attribute_1、Attribute_2 和 Attribute_3 包含分类数据 - option_1 或 option_2 或 option_3 的每一行。
I want to create a count plot on the same plot for all the attributes.我想在同一个图上为所有属性创建一个计数图。 I am able to do it for one column by:我可以通过以下方式为一列做到这一点:
sns.countplot(x="Attribute_1", data=df);
I can individually create for each of the attributes, but what I am looking for it that on the same plot I can have count plot for all the attributes.我可以为每个属性单独创建,但是我正在寻找的是在同一个图上我可以为所有属性计数图。 ie X-axis will have attributes, and each attribute will have three count plot.即 X 轴将有属性,每个属性将有三个计数图。
Seaborn usually works best with long form datasets. Seaborn 通常最适合长格式数据集。 Ie instead of 3 columns with different options for each attribute you would have two columns, one for the options and one for the attributes.即,不是每个属性具有不同选项的 3 列,您将有两列,一列用于选项,另一列用于属性。 This can easily be created via pd.melt
.这可以通过pd.melt
轻松创建。 Then the hue
value can be used on the "options" column:然后可以在“选项”列上使用hue
值:
sns.countplot(x="variable", hue="value", data=pd.melt(df))
Complete example:完整示例:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
a= np.random.choice(["option_{}".format(i) for i in [1,2,3]], size=(12,3))
df = pd.DataFrame(a, columns=["Attribute_{}".format(i) for i in list("ABC")])
sns.countplot(x="variable", hue="value", data=pd.melt(df))
plt.show()
Equally you can interchange x
and hue
:同样,您可以互换x
和hue
:
sns.countplot(x="value", hue="variable", data=pd.melt(df))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.