简体   繁体   中英

Scatter Plot with different color for positive and negative values

Here is my problem

This is a sample of my two DataFrames (I have 30 columns in reality)

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.DataFrame({"Marc":[6,0,8,-30,-15,0,-3],
                   "Elisa":[0,1,0,-1,0,-2,-4],
                   "John":[10,12,24,-20,7,-10,-30]})

df1 = pd.DataFrame({"Marc":[8,2,15,-12,-8,0,-35],
                   "Elisa":[4,5,7,0,0,1,-2],
                   "John":[20,32,44,-30,15,-10,-50]})

I would like to create a scatter plot with two different colors: 1 color if the scores of df1 are negative and one if they are positive, but I don't really know how to do it.

I already did that by using matplotlib

plt.scatter(df,df1);

And I also checked this link Link but the problem is that I have two Pandas Dataframe and not numpy array as on this link. Hence the I can't use the c= np.sign(df.y) method. I would like to keep Pandas DataFrame as I have many columns but I really stuck on that.

If anyone has a solution, you are welcome!

You can pass the color array in, but it seems to work with 1D array only:

# colors as stated
colors = np.where(df1<0, 'C0', 'C1')

# stack and ravel to turn into 1D
plt.scatter(df.stack(),df1.stack(), c=colors.ravel())

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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