Jack022
Jack022

Reputation: 1287

Matplotlib - set Alpha and color dynamically

I'm plotting a scatter plot from a Pandas dataframe in Matplotlib. Here is what the dataframe looks like:

       X  Y    R
0      1  945  1236.334519
0      1  950   212.809352
0      1  950   290.663847
0      1  961   158.156856

And here is how i'm plotting the Dataframe:

ax1.scatter(myDF.X, myDF.Y, s=20, c='red', marker='s', alpha=0.5)

My problem is that i want to change how the marker is plotted according to how high or low the value of R is.

Example: if R is higher than 1000 (as it is in the first row of my example), color should be yellow instead of red and alpha should be 0.8 instead of 0.5. If R is lower than 1000, color should be blue and alpha should be 0.4 and so on.

Is there any way to do that or can i only use different dataframe with different data? Thanks in advance!

Upvotes: 1

Views: 2564

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

You can do a custom RGBA color array:

colors = [(1,1,0,0.8) if x>1000 else (1,0,0,0.4) for x in df.R]

plt.scatter(df.X,df.Y, c=colors)

Output:

enter image description here

Upvotes: 2

Related Questions