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

2024-03-21

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

数据框看起来像:

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

我希望散点图中的点具有不同的颜色,具体取决于动画行中的值。
所以动画 = 1 = 黄色
动画 = 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)

This results in a slider which makes it hard to tell the difference. enter image description here


您还可以通过将数组传递给 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python根据值绘制不同颜色的散点图 的相关文章

随机推荐