我有一个包含分类数据的数据框:
colour direction
1 red up
2 blue up
3 green down
4 red left
5 red right
6 yellow down
7 blue down
我想根据类别生成一些图形,例如饼图和直方图。是否可以不创建虚拟数值变量?就像是
df.plot(kind='hist')
Answers:
df['colour'].value_counts()[['green', 'yellow', 'blue', 'red']]
您也可以使用countplot
from seaborn
。此程序包可pandas
用于创建高级绘图界面。它免费为您提供良好的样式和正确的轴标签。
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
sns.countplot(df['colour'], color='gray')
它还支持一些技巧,以正确的颜色为条形着色
sns.countplot(df['colour'],
palette={color: color for color in df['colour'].unique()})
要在同一图上绘制多个分类特征作为条形图,我建议:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
{
"colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
"direction": ["up", "up", "down", "left", "right", "down", "down"],
}
)
categorical_features = ["colour", "direction"]
fig, ax = plt.subplots(1, len(categorical_features))
for i, categorical_feature in enumerate(df[categorical_features]):
df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)
fig.show()
df["colour"].value_counts().plot(kind='bar')
作为替代方案