0

我正在循环中动态更新绘图:

dat=[0, max(X[:, 0])]
fig = plt.figure()
ax = fig.add_subplot(111)
Ln, = ax.plot(dat)
Ln2, = ax.plot(dat)

plt.ion()
plt.show() 
for i in range(1, 40):
            ax.set_xlim(int(len(X[:i])*0.8), len(X[:i])) #show last 20% data of X
            Ln.set_ydata(X[:i])
            Ln.set_xdata(range(len(X[:i])))
            
            Ln2.set_ydata(Y[:i])
            Ln2.set_xdata(range(len(Y[:i])))
            
            plt.pause(0.1)

但现在我想以不同的方式更新它:附加一些值并以其他颜色显示它们:

X.append(other_data)
# change colour just to other_data in X

结果应如下所示:

最终情节

我怎么能那样做?

4

1 回答 1

1

看看我发布的链接。Linesegments可用于在特定位置以不同方式绘制颜色。如果您想实时执行此操作,您仍然可以使用线段。我把它留给你。

在此处输入图像描述

# adjust from https://stackoverflow.com/questions/38051922/how-to-get-differents-colors-in-a-single-line-in-a-matplotlib-figure
import numpy as np, matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

# my func
x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = 3000 * np.sin(x)

# select how to color
cmap = ListedColormap(['r','b'])
norm = BoundaryNorm([2000,], cmap.N)

# get segments
xy = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])

# control which values have which colors
n = y.shape[0]
c = np.array([plt.cm.RdBu(0) if i < n//2 else plt.cm.RdBu(255) for i in range(n)])
# c = plt.cm.Reds(np.arange(0, n))


# make line collection
lc = LineCollection(segments, 
                    colors = c
#                     norm = norm,
               )
# plot
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.axvline(x[n//2], linestyle = 'dashed')

ax.annotate("Half-point", (x[n//2], y[n//2]), xytext = (4, 1000),
   arrowprops = dict(headwidth = 30))
fig.show()
于 2020-12-22T11:13:46.820 回答