简体   繁体   English

用不同颜色的正负值散布 Plot

[英]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)这是我的两个 DataFrame 的示例(实际上我有 30 列)

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.我想用两个不同的 colors 创建一个散点图 plot:如果 df1 的分数为负数,则为 1 种颜色,如果为正数,则为一种颜色,但我真的不知道该怎么做。

I already did that by using matplotlib我已经通过使用 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.而且我还检查了此链接链接,但问题是我有两个 Pandas Dataframe 而不是 numpy 数组,如此链接。 Hence the I can't use the c= np.sign(df.y) method.因此我不能使用c= np.sign(df.y)方法。 I would like to keep Pandas DataFrame as I have many columns but I really stuck on that.我想保留 Pandas DataFrame 因为我有很多专栏,但我真的坚持下去。

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: Output:

在此处输入图像描述

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

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