Python散点图根据值绘制不同的颜色

时间:2017-04-18 21:24:22

标签: python pandas matplotlib plot

我有一个数据框,我想制作一个散点图。

数据框如下所示:

       year  length  Animation
0      1971     121       1
1      1939      71       1
2      1941       7       0
3      1996      70       1
4      1975      71       0

我希望散点图中的点是不同的颜色,具体取决于动画行中的值 所以动画= 1 =黄色
animation = 0 =黑色
或类似的东西

我尝试了以下操作:

dfScat = df[['year','length', 'Animation']]
dfScat = dfScat.loc[dfScat.length < 200]    
axScat = dfScat.plot(kind='scatter', x=0, y=1, alpha=1/15, c=2)

这导致滑块很难区分。 enter image description here

2 个答案:

答案 0 :(得分:5)

使用c

中的scatter参数
df.plot.scatter('year', 'length', c='Animation', colormap='jet')

enter image description here

答案 1 :(得分:4)

您还可以通过将数组传递给c =来为点指定离散颜色 像这样:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

d = {"year"      : (1971, 1939, 1941, 1996, 1975),
     "length"    : ( 121,   71,    7,   70,   71),
     "Animation" : (   1,    1,    0,    1,    0)}

df = pd.DataFrame(d)
print(df)

colors = np.where(df["Animation"]==1,'y','k')
df.plot.scatter(x="year",y="length",c=colors)
plt.show()

这给出了:

   Animation  length  year
0          1     121  1971
1          1      71  1939
2          0       7  1941
3          1      70  1996
4          0      71  1975

enter image description here