可视化一列中的数据

时间:2017-04-21 18:44:26

标签: python matplotlib dataframe visualization jupyter

假设我有一个数据框,其中一列为Gender,其中包含类似 -

的值
male
female
female
empty 
male
female

如何使用matplotlib以条形图或饼图的形式显示此数据,以显示男性和女性的数量/百分比?

2 个答案:

答案 0 :(得分:2)

最简单的选择可能是在列上使用value_count并将结果绘制为条形图。

import pandas as pd
import matplotlib.pyplot as plt

a = ["male","female", "female", "empty","male","female"]
df = pd.DataFrame(a, columns= ["gender"])

df["gender"].value_counts().plot.bar()

plt.show()

enter image description here

同样可以绘制饼图,

df["gender"].value_counts().plot.pie()
plt.gca().set_aspect("equal")

enter image description here

允许更精细调整的另一个选项是使用matplotlib,如下所示:

import pandas as pd
import matplotlib.pyplot as plt

a = ["male","female", "female", "empty","male","female"]
df = pd.DataFrame(a, columns= ["gender"])

labels = []
for i, dfi in enumerate(df.groupby(["gender"])):
    labels.append(dfi[0])
    plt.bar(i, dfi[1].count(), label=dfi[0])
plt.xticks(range(len(labels)), labels)
plt.legend()
plt.show()

enter image description here

答案 1 :(得分:0)

使用本机Pandas功能:

a = ["male","female", "female", "empty","male","female"]
df = pd.DataFrame(a, columns= ["gender"])
_ = df.groupby('gender').size().plot(kind='pie', legend=True)

enter image description here