Matplotlib:在单个图上绘制两列或更多列的计数图 [英] Matplotlib: Plot countplot for two or more column on single plot
问题描述
我的数据帧,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
此处的 Attribute_1、Attribute_2 和 Attribute_3 包含分类数据 - 每一行的 option_1 或 option_2 或 option_3.
Here Attribute_1, Attribute_2 and Attribute_3 contains categorical data - option_1 or option_2 or option_3 for each of the rows.
我想在同一个图上为所有属性创建一个计数图.我可以通过以下方式在一列中做到这一点:
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);
我可以为每个属性单独创建,但我正在寻找的是在同一个图上我可以为所有属性计算图.即X轴将具有属性,每个属性将具有三个计数图.
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. i.e X-axis will have attributes, and each attribute will have three count plot.
推荐答案
Seaborn 通常最适合长格式数据集.IE.而不是为每个属性分配不同选项的3列,您将有两列,一列用于选项,一列用于属性.这可以通过 pd.melt
轻松创建.然后可以在选项"上使用 hue
值.列:
Seaborn usually works best with long form datasets. I.e. instead of 3 columns with different options for each attribute you would have two columns, one for the options and one for the attributes. This can easily be created via pd.melt
. Then the hue
value can be used on the "options" column:
sns.countplot(x="variable", hue="value", data=pd.melt(df))
完整示例:
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()
同样,您可以互换 x
和 hue
:
sns.countplot(x="value", hue="variable", data=pd.melt(df))
这篇关于Matplotlib:在单个图上绘制两列或更多列的计数图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!