1

This is my code

import matplotlib.pyplot as plt
import matplotlib.animation as animation

from matplotlib import style

style.use('fivethirtyeight')


def animate(i):
    graph_data = open('data.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []

    for line in lines:
        if len(line) > 1:
            x, y = map(int, line.split(','))
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs,ys)

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

ani = animation.FuncAnimation(fig, animate, interval=30000)
plt.show()

data.txt and data2.txt are just like:

0,1040
1,1074
2,1106
3,1123
4,1093
5,1067
6,1099
7,1121
8,1139

Now I have another data2.txt file and I need to plot the graph in the same figure like "overlapping". How to do this with this code?

  • Hi Botticelli69. Welcome to StackOverflow. Could you please edit your question and paste files: data.txt and data2.txt ? The better your question is, the easier it gets for someone to answer it. Please read: https://stackoverflow.com/help/how-to-ask – greenmarker Jun 21 '20 at 12:19
  • oh yeah sorry! Just edited – Botticelli69 Jun 21 '20 at 12:34
  • 1
    Does this answer your question? [How to plot multiple functions on the same figure, in Matplotlib?](https://stackoverflow.com/questions/22276066/how-to-plot-multiple-functions-on-the-same-figure-in-matplotlib) – Deepthought Jun 21 '20 at 12:42

1 Answers1

0

You can make use of matplotlib's interactive mode by invoking plt.ion(). Assuming your files are named in the format data {data1, data2, data3..}, store them as a list using glob. You can then get overlapping lines read from the different files as shown here:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
import glob

style.use('fivethirtyeight')
#data files stored as a list in files
files=glob.glob('*data*')

fig, ax = plt.subplots()
plt.ion()
plt.show()

for i in files:
    x,y = np.loadtxt(i,unpack=True,delimiter=',')
    line = ax.plot(x,y,label=i)
    plt.gcf().canvas.draw()
    plt.legend(loc=2)
    plt.pause(1)

enter image description here

Sameeresque
  • 2,464
  • 1
  • 9
  • 22
  • Yes it works! But I need the graph to stay rather than disappear after 1 second, and it need to process data in real time – Botticelli69 Jun 22 '20 at 12:21