[英]Python Matplotlib how to plot multiple graph in the same figure
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: data.txt 和 data2.txt 就像:
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".现在我有另一个 data2.txt 文件,我需要 plot 同图中的图形,如“重叠”。 How to do this with this code?
如何使用此代码执行此操作?
You can make use of matplotlib's interactive mode by invoking plt.ion()
.您可以通过调用
plt.ion()
来使用 matplotlib 的交互模式。 Assuming your files are named in the format data {data1, data2, data3..}, store them as a list using glob
.假设您的文件以data {data1, data2, data3..} 格式命名,请使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.