[英]matplotlib color lines according to magnitude
I have some lines where each point on the line is assigned a certain magnitude.我有一些线,线上的每个点都被分配了一定的大小。 I would like to plot the lines with colors corresponding to that magnitude.我想用与该幅度相对应的颜色绘制线条。 There is a way of doing something similar with scatter, but this only plots color coded points.有一种方法可以用 scatter 做类似的事情,但这只会绘制颜色编码的点。
I would prefer the scatter to show lines instead, because it would make things look a lot nicer when zooming in. Increasing the number of points is not an option for me, because in my real world problem this is too computationally expensive.我更喜欢散点图来显示线条,因为它会使放大时看起来更好。增加点数对我来说不是一个选择,因为在我的现实世界问题中,这在计算上太昂贵了。 Interpolation between the points could be done by simple interpolation between the adjacent points.点之间的插值可以通过相邻点之间的简单插值来完成。
Small example of a scatter plot散点图的小例子
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
z = np.cos(x)
y2 = np.sin(x)+0.4
z2 = 0.5*np.cos(2*x)
x3 = np.hstack((x,x))
y3 = np.hstack((y,y2))
z3=np.hstack((z,z2))
fig = plt.figure()
ax = fig.add_subplot(111)
#ax.scatter(x, y, c=z)
#ax.scatter(x, y2, c=z2)
sc = ax.scatter(x3, y3, c=z3)
cbar = fig.colorbar(sc)
plt.show()
You can split the line into some small segments, and then set different colors to each segment according to some value.您可以将线条分割成一些小段,然后根据某个值为每个段设置不同的颜色。 For performance reason, you can use LineCollection .出于性能原因,您可以使用LineCollection 。 The following code is for your reference:以下代码供您参考:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as mcollection
import matplotlib.colors as mcolors
def seg_plot(ax, X, Y, Z, cmap=None, alpha=None, **kargs):
if cmap is None:
cmap = plt.get_cmap()
P = np.array([X, Y]).T.reshape(-1, 1, 2)
S = np.concatenate([P[:-1], P[1:]], axis=1)
norm = mcolors.Normalize(vmin=Z.min(), vmax=Z.max())
C = cmap(norm(Z))
L = mcollection.LineCollection(S, color=C, alpha=alpha, **kargs)
ax.add_collection(L)
ax.set_xlim(X.min(), X.max())
ax.set_ylim(1.1*Y.min(), 1.1*Y.max())
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
z = np.cos(x)
y2 = np.sin(x)+0.4
z2 = 0.5*np.cos(2*x)
fig, ax = plt.subplots()
seg_plot(ax, x, y, z, linewidth=2)
seg_plot(ax, x, y2, z2, linewidth=2)
ax.set_ylim([-2, 2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.