简体   繁体   English

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

[英]Python scatter plot different colors depending on value

I have a dataframe which i want to make a scatter plot of. 我有一个要绘制散点图的数据框。

the dataframe looks like: 数据框如下所示:

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

I want the points in my scatter plot to be a different color depending the value in the Animation row. 我希望散点图中的点是不同的颜色,具体取决于“动画”行中的值。
So animation = 1 = yellow 所以动画= 1 =黄色
animation = 0 = black 动画= 0 =黑色
or something similiar 或类似的东西

I tried doing the following: 我尝试执行以下操作:

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. 这样就产生了一个滑块,很难区分出差异。 在此处输入图片说明

You can also assign discrete colors to the points by passing an array to c= Like this: 您还可以通过将数组传递给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()

This gives: 这给出:

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

在此处输入图片说明

Use the c parameter in scatter scatter使用c参数

df.plot.scatter('year', 'length', c='Animation', colormap='jet')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM