Skip to main content
 首页 » 编程设计

python之如何在 Python 中绘制 "Colormap/Heatmap"多线图(matplotlib)

2024年10月24日35小虾米

我正在尝试使用 matplotlib 在 Python 的一个 3D 图形上绘制空间中的多条线(每条线连接一对点),我希望每条线根据其长度(即,最长的线是红色的,中间长度的线是橙色的,等等)。

我计算了所有的线长。

我的点坐标在单独的数组中进行,如下所示:

x1 = # all of the x coordinates of the primary points 
y1 = # all of the y coordinates of the primary points 
z1 = # all of the z coordinates of the primary points 
 
x2 = # all of the x coordinates of the secondary points 
y2 = # all of the y coordinates of the secondary points 
z2 = # all of the z coordinates of the secondary points 

每条线都有端点 (x1[i],y1[i],z1[i]) 和 (x2[i],y2[i],z2[i] ) 和 i 是该行的索引。

我如何使用热图或其他一些 Python 函数为每一行相应地着色?我想我了解热图如何用于绘制一组数据,但我试图绘制单独的线条并根据一些引用长度(即 lenth_max,这将是“ HitTest 的” "长度)。

请您参考如下方法:

这是一个带有一些随机长度线的示例。必须计算线条的距离,然后将其归一化到与颜色图相同的范围。我选了'hot' , 但你可以选择任何一个,'hot' 后面的 '_r' 反转颜色图。

import matplotlib.pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.cm as mplcm 
import matplotlib.colors as colors 
import numpy as np 
from random import randint 
 
fig = plt.figure() 
ax = Axes3D(fig) 
 
num_lines = 50 
lines, distances = [], [] 
for x in range(0, num_lines): 
    xs = [0, randint(10, 150)] 
    ys = [0, 5] 
    zs = [0, randint(10,60)] 
    lines.append([xs, ys, zs]) 
 
    distance = np.sqrt((xs[0]-xs[1])**2+(ys[0]-ys[1])**2+(zs[0]-zs[1])**2)  # calculate length of a line 
    distances.append(distance) 
 
distances_normalised = distances / (np.max(distances)/num_lines)  # normalise lengths of lines 
cNorm = colors.Normalize(vmin=0, vmax=num_lines - 1) 
 
cm = plt.get_cmap('hot_r') 
scalarMap = mplcm.ScalarMappable(norm=cNorm, cmap=cm) 
 
for dist, line in enumerate(lines): 
    ax.plot(line[0], line[1], line[2], color=scalarMap.to_rgba(distances_normalised[dist])) 
 
ax.set_xlabel('x') 
ax.set_ylabel('y') 
ax.set_zlabel('z') 
 
plt.show()