简体   繁体   English

不同颜色的散点图

[英]scatter plot with different color

I am new to matplotlib and trying to plot this liner regression with customized color for a specific independent variable: 我是matplotlib的新手,并尝试使用特定自定义变量的自定义颜色绘制此线性回归:

colors=['red','blue','green','black']
X=array([[1000],[2000],[3000],[4500]]
y=array([[200000],[200000],[200000],[200000]]

plt.scatter(X, y, color = colors[0])
plt.plot(X, lin_reg.predict(X), color = 'blue')
plt.xlabel('X')
plt.ylabel('y')
plt.show()

I need to set the color to black when X==3000 so I am using np.where: 当X == 3000时,我需要将颜色设置为黑色,所以我在使用np.where:

colors_z=(np.where(X==3000,colors[4],colors[0]))
plt.scatter(X, y, color = colors_z)

But I am getting color error. 但是我收到颜色错误。 any Idea what I am doing wrong? 任何想法我在做什么错? Thanks 谢谢

I think this does what you're looking for; 我认为这可以满足您的需求; using np.where is a bit overkill for this purpose: 为此目的,使用np.where有点np.where正:

X = [1000, 2000, 3000, 4500]
y = [200000, 3000, 200000, 200000]
colors = list(map(lambda x: 'r' if x == 3000 else 'b', X))

plt.scatter(X, y, color=colors)
plt.xlabel('X')
plt.ylabel('y')
plt.show()

You've set colors_z to include colors[4] but there are only 4 colors in the list colors. 您已将colors_z设置为包括colors [4],但列表颜色中只有4种颜色。 The index for colors_z should be out of range. colors_z的索引应超出范围。 I'd dump the np.where in favor of a simple if statement or ternary operator. 我将转储np.where,转而使用简单的if语句或三元运算符。 Something like: 就像是:

# ternary operator example
plt.scatter(x, y, color = [colors[3] if x == 3000 else colors[0] for i in x])

Note that this will only work when x is exactly == 3000, but it doesn't throw a syntactical error on my console, so it should work in your regression. 请注意,这仅在x精确地等于== 3000时才起作用,但不会在我的控制台上引发语法错误,因此它应该在回归中起作用。

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

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