将二维散点图中的点连接为第三维颜色

时间:2019-11-28 10:36:26

标签: python matplotlib scatter-plot

假设我有以下数据集:

x = np.arange(150000,550000,100000)
y = np.random.rand(7*4)
z = [0.6,0.6,0.6,0.6,0.7,0.7,0.7,0.7,0.8,0.8,0.8,0.8,0.9,0.9,0.9,0.9,1.0,1.0,1.0,1.0,1.1,1.1,1.1,1.1,1.2,1.2,1.2,1.2]

x_ = np.hstack([x,x,x,x,x,x,x])

我正在做一个散点图:

plt.figure()
plt.scatter(x_,y,c=z)
plt.colorbar()
plt.set_cmap('jet')
plt.xlim(100000,500000)
plt.show()

但是,我想连接相同颜色的点。我尝试仅将plt.plot与相同的变量一起使用,但是它将所有点连接在一起,而不是仅将黄色点和黄色点连接起来。

感谢您的帮助。

编辑:

z轴是离散的,我事先知道这些值。我也知道我可以多次调用plt.plot()方法来画线,但我希望可能还有另一种方法。

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您会有一个x值列表,并且对于每个x,都有一些y关联,每个x,y具有特定的z值。 z值属于一个有限集(或可以四舍五入以确保只有一个有限集)。

因此,我创建了x,y和z的副本,并通过z同时对其进行了排序。 然后,循环遍历z数组,收集x,y,每次z更改时,都可以绘制属于该颜色的所有线条。 为了不需要特殊的步骤来绘制最后一组线,我附加了一个哨兵。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(150000,550000,100000)
y = np.random.rand(7*4)
z = [0.6,0.6,0.6,0.6,0.7,0.7,0.7,0.7,0.8,0.8,0.8,0.8,0.9,0.9,0.9,0.9,1.0,1.0,1.0,1.0,1.1,1.1,1.1,1.1,1.2,1.2,1.2,1.2]
z_min = min(z)
z_max = max(z)

x_ = np.hstack([x,x,x,x,x,x,x])

zs = [round(c, 1) for c in z]  # make sure almost equal z-values are exactly equal
zs, xs, ys = zip( *sorted( zip(z, x_, y) ) )  # sort the x,y via z
zs += (1000,) # add a sentinel at the end that can be used to stop the line drawing
xs += (None, )
ys += (None, )

plt.set_cmap('plasma')
cmap = plt.get_cmap()  # get the color map of the current plot call with `plt.get_cmap('jet')`
norm = plt.Normalize(z_min, z_max) # needed to map the z-values between 0 and 1

plt.scatter(x_, y, c=z, zorder=10)  # z-order: plot the scatter dots on top of the lines
prev_x, prev_y, prev_z = None, None, None
x1s, y1s, x2s, y2s = [], [], [], []
for x0, y0, z0 in zip(xs, ys, zs):
    if z0 == prev_z:
        x1s.append(prev_x)
        y1s.append(prev_y)
        x2s.append(x0)
        y2s.append(y0)
    elif prev_z is not None:  # the z changed, draw the lines belonging to the previous z
        print(x1s, y1s, x2s, y2s)
        plt.plot(x1s, y1s, x2s, y2s, color=cmap(norm(prev_z)))
        x1s, y1s, x2s, y2s = [], [], [], []
    prev_x, prev_y, prev_z = x0, y0, z0

plt.colorbar()
plt.show()

这是您的意思吗? the resulting plot

答案 1 :(得分:1)

使用<distributionManagement> <repository> <id>github</id> <url>https://maven.pkg.github.com/stirante/lol-client-java-api</url> </repository> </distributionManagement> 更容易:

LineCollection

enter image description here