Python 使用matplotlib和更新文本文件生成实时打印
我试图使用Python 使用matplotlib和更新文本文件生成实时打印,python,matplotlib,Python,Matplotlib,我试图使用matplotlib中的animation函数生成数据的实时绘图。我通过以下链接参考本教程以获得支持: 我正在读取的data.txt文件每秒都会用新数据更新。输入的数据如下所示:[0.0263671875,0.03515625,1.0087890625][0.01171875,0.0146484375,0.4404296875][0.01171875,0.0146484375,0.4404296875]。。。等等 动画函数的前三行提取每个数组中的第三个元素: data = pd.rea
matplotlib
中的animation
函数生成数据的实时绘图。我通过以下链接参考本教程以获得支持:
我正在读取的data.txt
文件每秒都会用新数据更新。输入的数据如下所示:[0.0263671875,0.03515625,1.0087890625][0.01171875,0.0146484375,0.4404296875][0.01171875,0.0146484375,0.4404296875]
。。。等等
动画函数的前三行提取每个数组中的第三个元素:
data = pd.read_csv("C:\\Users\\Desktop\\data.txt", sep="\[|\]\[|\]",engine = 'python', header = None)
data = data.iloc[0]
data = data.astype(str).apply(lambda x: x.split(',')[-1]).astype(float)
data.pop(0)
我在Jupyter笔记本中验证了这段代码,输出如下(这就是我要寻找的):
我的第一个挑战来自我试图实时生成图形的时候。我的数据没有x轴(时间轴)。因此,我的第一个障碍之一是在数据流更新时生成一个人工x轴。以上链接教程中的代码用作模板。我将指出我正在努力为我的特定目的修改的领域
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
data = pd.read_csv("C:\\Users\\Desktop\\data.txt", sep="\[|\]\[|\]",engine = 'python', header = None)
data = data.iloc[0]
data = data.astype(str).apply(lambda x: x.split(',')[-1]).astype(float)
data.pop(0)
xar = []
yar = []
for eachLine in data:
if len(eachLine)>1:
x,y = eachLine.split(',')
xar.append(int(x))
yar.append(int(y))
ax1.clear()
ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
除了人工创建x轴编号以便创建绘图外,我还需要修改for循环:
xar = []
yar = []
for eachLine in data:
if len(eachLine)>1:
x,y = eachLine.split(',')
xar.append(int(x))
yar.append(int(y))
在链接中提供的示例中,它们的数据流有一个x
和y
数据点,由一列分隔。我拥有的数据流只是一个值
我将如何修改我的代码以(1)添加一个适当的x轴以便能够打印,(2)正确地通过for循环以便将值附加到xar
和yar
以实时打印图形
编辑1
我尝试了以下方法,但不起作用,需要一些帮助。。。但这是我的第一枪。我得到一个错误:
if len(eachLine)>1:
TypeError: object of type 'numpy.float64' has no len()
我的代码如下:
def animate(i):
data = pd.read_csv("C:\\Users\\Desktop\\data.txt", sep="\[|\]\[|\]",engine = 'python', header = None)
data = data.iloc[0]
data = data.astype(str).apply(lambda x: x.split(',')[-1]).astype(float)
data.pop(0)
xar = []
yar = []
for j in range(len(data)):
xar.append(j)
for k in range(len(data)):
yar.append(data.iloc[k])
for eachLine in data:
if len(eachLine)>1:
x,y = eachLine.split('')
xar.append(int(x))
yar.append(int(y))
ax1.clear()
ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1)
plt.show()
谢谢大家! 对读入的数据一无所知,这使得理解问题变得困难。但是,一般情况下,您会从数据帧中绘制一列,如下所示
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def animate(i):
data = pd.read_csv(...)
yar = data[ "column to plot" ]
xar = range(len(data))
ax.clear()
ax.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=10)
plt.show()
代码看起来很好。我完全不理解这个问题,问题是输入的数据流看起来就像我的Jupyter笔记本的输出。它只有我的“y值”。我目前没有任何x值来构建我的绘图。我认为你的问题过于关注你不想使用的示例,而不是你实际拥有的案例。在任何情况下,您都可能希望提供有关该问题的详细信息。