Matplotlib线图:高曲率的着色区域

时间:2016-03-10 14:51:06

标签: python matplotlib colors

我想在3D空间和高曲率的颜色区域中绘制一条线。现在我有一个使用离散散点图的解决方法:

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cmx

mpl.rcParams['legend.fontsize'] = 10

data = np.loadtxt('data',usecols=range(0,4))
x = data[:,0]
y = data[:,1]
z = data[:,2]
cs = data[:,3]

colorsMap='jet'
cm = plt.get_cmap(colorsMap)
cNorm = mpl.colors.Normalize(vmin=min(cs), vmax=max(cs))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)

fig = plt.figure()
scalarMap.set_array(cs)
fig.colorbar(scalarMap)


ax = fig.gca(projection='3d')
ax.scatter(x, y, z, c=scalarMap.to_rgba(cs), label='scatter curve')
ax.legend()

plt.show()

但我宁愿有一个连续的线图。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

根据您拥有的数据点数量,您可能能够解决这个问题。例如,请考虑下面生成的3D螺旋数据,以替换为data.txt

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cmx

mpl.rcParams['legend.fontsize'] = 10

theta = np.linspace(-4 * np.pi, 4 * np.pi, 1000)
z = np.linspace(-2, 2, 1000)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
cs = 1/r

colorsMap='jet'
cm = plt.get_cmap(colorsMap)
cNorm = mpl.colors.Normalize(vmin=min(cs), vmax=max(cs))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)

fig = plt.figure()
scalarMap.set_array(cs)


ax = fig.gca(projection='3d')
ax.scatter(x, y, z, c=scalarMap.to_rgba(cs), marker='_', s=1)
plt.colorbar(scalarMap)

plt.show()

enter image description here

如果您的数据点的采样频率不是"紧",那么这看起来不太好看。但是,您可以使用此接受answer来改进此问题。