pandas 使用自定义颜色设置散点图中正值和负值的颜色

rta7y2nd  于 2022-12-09  发布在  其他
关注(0)|答案(1)|浏览(189)

对于Matplotlib中的散点图,我想用绿色显示正值(y),用红色显示负值(y)。如果我设置z〉0,并将其放入(c)的参数中,默认情况下,它会为正值和负值给予两种不同的颜色。但我想将这些颜色更改为绿色表示正值,红色表示负值。我该怎么做呢?

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

z = y > 0

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

plt.show()
ryevplcw

ryevplcw1#

你可以重新排列你的数据,并将其分为正值和负值。

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()

相关问题