简体   繁体   English

使用具有 2 种自定义颜色的 Matplotlib 在散点图中设置正值和负值的颜色

[英]Setting Colors For Positive and Negative Values in Scatter Plot with Matplotlib with 2 Custom Colors

For a scatter plot in Matplotlib, I want show positive (y) values in green color, and negative (y) values in red color.对于 Matplotlib 中的散点图,我想以绿色显示正 (y) 值,以红色显示负 (y) 值。 If I set the value z>0, and put this in the argument of (c), by default it does give me 2 different colors for the positive values and negative values.如果我设置值 z>0,并将其放入 (c) 的参数中,默认情况下它确实为我提供了 2 种不同颜色的正值和负值。 But i want to change those colors to my choice of Green for Positive, and Red for Negative.但我想将这些颜色更改为我选择的绿色为正,红色为负。 How can I do this?我怎样才能做到这一点?

x = [4, 5, 11, 15] 
y = [17, -14, 13, -19]

z = y > 0

plt.scatter(x, y, c=z)

plt.show()

You can rearrange your data and split into positive and negative values.您可以重新排列数据并拆分为正值和负值。 As part of this answer I suggest you to use np.array instead of using the dtype list because it is much easier to use indices in this case作为此答案的一部分,我建议您使用np.array而不是使用np.array list因为在这种情况下使用索引要容易得多

import numpy as np
# data
x = np.array([ 4, 5, 11, 15 ])
y = np.array([ 17, -14, 13, -19 ])
z = 0

valid_pos = []  # preallocate appending variable
valid_neg = []
for i in range(0, x.shape[0]):  # 0 for number of lines, 1 for number of columns
    if y[i] >= z:
        valid_pos.append(i)
    elif y[i] < z:
        valid_neg.append(i)
x_pos = x[valid_pos]  # rearrange your data
y_pos = y[valid_pos]
x_neg = x[valid_neg]
y_neg = y[valid_neg]

# plotting figure
plt.figure()
plt.scatter(x_pos, y_pos, c='g')
plt.scatter(x_neg, y_neg, c='r')
plt.show()

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

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