Set*_*ti7 0 python matplotlib python-3.x
我正在尝试使用Matplotlib使用Python做实时图形绘制(遵循本教程)。但是X轴的顺序在我的代码中是错误的,因为它从1开始,依次为10、11,然后返回2、3、4、5 ...
我只是在教程中复制了代码和数字,但是得到了不同的结果。这是它为我显示的图形:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
def animate(i):
graph_data = open("animation_file.txt", 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(y)
ax1.clear()
ax1.plot(xs, ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
Run Code Online (Sandbox Code Playgroud)
这是“ animation_file.txt”:
1, 5
2, 3
3, 4
4, 7
5, 4
6, 3
7, 6
8, 7
9, 4
10,4
11, 2
Run Code Online (Sandbox Code Playgroud)
您将x和y值视为字符串,而应将它们解析为数字:
xs.append(float(x))
ys.append(float(y))
Run Code Online (Sandbox Code Playgroud)
或者:
x, y = map(float, line.split(','))
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
2527 次 |
| 最近记录: |