【问题标题】:Append data with different colour in matplotlib in real time在matplotlib中实时追加不同颜色的数据
【发布时间】:2020-12-22 09:57:03
【问题描述】:

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

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

结果应该是这样的:

我该怎么做?

【问题讨论】:

  • this 回答你的问题了吗?
  • @cvanelteren 没有那么多,因为它包含一个可以改变颜色的范围;我只是在寻找一个无边界的颜色变化,但谢谢!

标签: python matplotlib matplotlib-animation


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-03
    • 2020-02-13
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    相关资源
    最近更新 更多