假设我有一个数据框,其中一列为Gender,其中包含类似 -
的值male
female
female
empty
male
female
如何使用matplotlib以条形图或饼图的形式显示此数据,以显示男性和女性的数量/百分比?
答案 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()
同样可以绘制饼图,
df["gender"].value_counts().plot.pie()
plt.gca().set_aspect("equal")
允许更精细调整的另一个选项是使用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()
答案 1 :(得分:0)