[英]How to add a data to the plot in matplotlib?
How can I have the line plot, with the data coming one by one?我怎样才能得到线图,数据一一出现? I have the code
我有代码
import matplotlib.pyplot as plt
plt.ion()
plt.plot(1, 2)
plt.pause(2.5)
plt.plot(2, 5)
plt.pause(2.5)
but it does not show the line, if I add 'o' option in plot
function or change the plot
function to scatter
function, it works fine, But I want a line with no markers, how can I do this?但它不显示线,如果我在
plot
函数中添加'o'选项或将plot
函数更改为scatter
点函数,它工作正常,但我想要一条没有标记的线,我该怎么做?
I tried the following code, according with my tests it works only if the plot is generated in an external window:我尝试了以下代码,根据我的测试,它仅在绘图是在外部窗口中生成时才有效:
import matplotlib.pyplot as plt
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(True)
x = [4, 1, 5, 3, 8]
y = [1, 2, 9, 0, 2]
ax.set_xlim(0, 9)
ax.set_ylim(-1, 10)
for j in range(1, len(x)):
X = [x[j-1], x[j]]
Y = [y[j-1], y[j]]
ax = plt.plot(X, Y, mew = 5, ms = 5)
# mew and ms used to change crosses size
plt.pause(1)# one second of delay
plt.show()
If you are working on Spyder, in order to make the intepreter generating an external window whenever you call a plot you have to type如果您正在使用 Spyder,为了让解释器在您调用绘图时生成外部窗口,您必须输入
%matplotlib qt
on the intepreter (and not into the script file!) BEFORE running the previous lines of code在解释器上(而不是在脚本文件中!)在运行前面的代码行之前
To respond to the comment about "deleting the current plot", and to improve upon Stefano's answer a bit, we can use Matplotlib's object-oriented interface to do this:为了回应关于“删除当前绘图”的评论,并稍微改进 Stefano 的回答,我们可以使用 Matplotlib 的面向对象接口来执行此操作:
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4, 5, 6]
y = [3, 1, 4, 1, 5, 9, 2]
fig, ax = plt.subplots()
ax.set(xlim=(min(x), max(x)), ylim=(min(y), max(y)))
plt.ion()
(line,) = ax.plot([], []) # initially an empty line
timestep = 0.5 # in seconds
for i in range(1, len(x) + 1):
line.set_data(x[:i], y[:i])
plt.pause(timestep)
plt.show(block=True)
This version uses a single Line2D
object and modifies its underlying data via set_data
.此版本使用单个
Line2D
对象并通过set_data
修改其基础数据。 Since Matplotlib doesn't have to draw multiple objects, just the one line, it should scale better once your data becomes large.由于 Matplotlib 不必绘制多个对象,只需绘制一条线,因此一旦数据变大,它应该可以更好地扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.