散点图中的颜色代码数据帧

时间:2018-04-14 12:09:33

标签: python pandas numpy matplotlib

假设我有以下数据框:

UIView

我想找到一种方法来对X Y Category 1 2 A 5 3 B -1 1 C 7 0 A 1 2 B ... df['X']的输出进行颜色编码,具体取决于其类别(df['Y'])。

到目前为止我已尝试过这个:

df['Category']

但它告诉我

cm = pd.unique(df['Category'])
plt.scatter(data['X'], data['Y'], c=cm)

2 个答案:

答案 0 :(得分:3)

使用更高级别的库(例如seaborn,特别是通过seaborn.lmplot执行此操作要简单得多:

import seaborn as sns

sns.lmplot(x=X, y=Y, huge='Category', data=df)

让它处理细节。

请参阅Plotting With Categorical Data,了解seaborn用于绘制分类数据的其他选项。

答案 1 :(得分:1)

您可以使用pandas图重塑数据帧。

df.set_index(['X','Category'])['Y'].unstack().plot(marker='o',linestyle='none')

输出:

enter image description here

或者你可以使用seaborn:

import seaborn as sns
_ = sns.pointplot(x='X',y='Y', hue='Category', data=df, linestyles='none')

输出:

enter image description here

相关问题