Matplotlib:对txt数据文件中的行散点进行动画处理

时间:2020-04-01 18:20:10

标签: python-3.x matplotlib matplotlib-animation

我正在尝试使用Python3和matplotlib创建线散点图的动画,并最终创建视频输出。线散布图数据将来自.txt数据文件,该文件是用“,”分隔的文本,并按时间/力/距离的顺序进行结构化。我已经使用轴标签成功生成了力与时间的关系图。我还成功地生成了力与时间,距离与时间,时间刻度对齐的子图。但是,当我尝试添加代码以生成动画时,它要么显示空白图,要么将数据绘制成静态图。我正在努力生成动画。我希望数据以时间为单位绘制(从左到右的动画),并以与数据相同的时间速率绘制(即1秒的数据以1秒的间隔在动画中显示)。动画正确后,我将导出视频文件。非常感谢任何提供帮助的人!

我不知道如何附加.txt文件,所以这是按时间/力/距离构造的数据:

文件名:Data_Example_Time_Force_Distance.txt

0,663,0
1,1366,0.254
2,1357,0.266
3,1263,0.251
4,1253,0.259
5,1259,0.252
6,1235,0.241
7,1218,0.262
8,1188,0.259
9,1268,0.287
10,1242,0.207
11,1280,0.259
12,1240,0.247
13,1229,0.414
14,1252,0.254
15,1227,0.267
16,1219,0.274
17,1193,0.281
18,1063,0.294
19,1244,0.256
20,1234,0.251
21,1211,0.271
22,1206,0.249
23,1211,0.246
24,3227,1.21
25,1800,2.321
26,1574,3.476
27,1649,4.583
28,1623,5.716
29,1442,6.855
30,1143,7.993
31,928,9.161
32,957,10.3
33,954,11.468
34,937,12.586
35,929,13.724
36,934,14.845
37,934,15.959
38,962,17.11
39,922,18.298
40,877,19.399
41,954,20.522
42,905,21.68
43,757,22.731
44,860,23.945
45,895,25.08
46,898,26.244
47,899,27.379
48,893,28.518
49,902,29.729
50,905,30.78
51,960,31.96
52,868,33.024
53,625,34.321
54,775,35.377
55,728,36.473
56,796,37.599
57,487,38.798
58,448,38.993

以下是我的力与时间的关系图的代码:

    # Numpy (data import, manipulation, export)
    import numpy as np
    # Matplotlib (create trends)
    import matplotlib.pyplot as plt

    # load the data file
    data_file = np.genfromtxt('Data_Example_Time_Force_Distance.txt', delimiter=',')

    # create time vector from imported data (starts from index 0)
    time = data_file[:,0]
    # parse force data from imported data
    force = data_file[:,1]

    # generate a figure
    plt.figure(1)
    plt.plot(time,force,color='tab:blue',linestyle='solid')
    # add text labels to the plot
    plt.legend(['Force (lbf)'])
    plt.xlabel('Time (s)')
    plt.ylabel('Force (lbf)')

    plt.show()

下面是我的子图的代码(2个图;上下),力随时间变化,距离随时间变化:

    # Numpy (data import, manipulation, export)
    import numpy as np
    # Matplotlib (create trends)
    import matplotlib.pyplot as plt

    # load the data file
    data_file = np.genfromtxt('Data_Example_Time_Force_Distance.txt', delimiter=',')

    # create time vector from imported data (starts from index 0)
    time = data_file[:,0]
    # parse force and distance data from imported data
    force = data_file[:,1]
    distance = data_file[:,2]

    # generate a figure
    fig, (ax1, ax2) = plt.subplots(2, sharex=True)
    fig.suptitle('Force and Distance vs Time')
    ax1.plot(time,distance)
    ax2.plot(time,force)

    plt.show()

0 个答案:

没有答案