Python散点图:基于X和Y值更改颜色

时间:2018-09-06 01:42:48

标签: python matplotlib plot scatter-plot colormap

我尝试使用cmaps和if / else语句重新创建附加的图像。

Example

我目前的尝试是基于this thread

中的建议

我尝试使用1.8 <= x <= 2.2,但出现错误。

这是我当前的以下代码:

import numpy as np
import matplotlib.pyplot as plt
N = 500
# center, variation, number of points
x = np.random.normal(2,0.2,N)
y = np.random.normal(2,0.2,N)
colors = np.where(x<=2.2,'r',np.where(y<=2.2,'b','b'))
plt.scatter(x , y, c=colors)
plt.colorbar()
plt.show()

1 个答案:

答案 0 :(得分:0)

要绘制该图,您需要传递一个具有每个点颜色的数组。在这种情况下,颜色是到点(2,2)的距离,因为分布以该点为中心。

import numpy as np
import matplotlib.pyplot as plt

N = 500
# center, variation, number of points
x = np.random.normal(2,0.2,N)
y = np.random.normal(2,0.2,N)

# we calculate the distance to (2, 2).
# This we are going to use to give it the color.
color = np.sqrt((x-2)**2 + (y-2)**2)

plt.scatter(x , y, c=color, cmap='plasma', alpha=0.7)
# we set a alpha
# it is what gives the transparency to the points.
# if they suppose themselves, the colors are added.

plt.show()

plot