从csv文件绘制多个图形并输出到单个pdf/svg
问题描述:
我有一些以下格式的 csv 数据.
I have some csv data in the following format.
Ln Dr Tag Lab 0:01 0:02 0:03 0:04 0:05 0:06 0:07 0:08 0:09
L0 St vT 4R 0 0 0 0 0 0 0 0 0
L2 Tx st 4R 8 8 8 8 8 8 8 8 8
L2 Tx ss 4R 1 1 9 6 1 0 0 6 7
我想使用列(Ln
、Dr
、Tg
、Lab
)绘制时间序列图作为键, 0:0n
字段作为时间序列图上的值.
I want to plot a timeseries graph using the columns (Ln
, Dr
, Tg
,Lab
) as the keys and the 0:0n
field as values on a timeseries graph.
我有以下代码.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.ylabel('time')
plt.xlabel('events')
plt.grid(True)
plt.xlim((0,150))
plt.ylim((0,200))
a=pd.read_csv('yourfile.txt',delim_whitespace=True)
for x in a.iterrows():
x[1][4:].plot(label=str(x[1][0])+str(x[1][1])+str(x[1][2])+str(x[1][3]))
plt.legend()
fig.savefig('test.pdf')
我在这里只显示了部分数据.我的完整数据集中有大约 200 个条目(200 行).上面的代码在一个图中绘制了所有图形.我更喜欢将每一行绘制在单独的图表中.
I have only shown a subset of my data here. I have around 200 entries (200 rows) in my full data set. the above code plots all graphs in a single figure. I would prefer each row to be plotted in a separate graph.
答
使用 subplot()
import matplotlib.pyplot as plt
fig = plt.figure()
plt.subplot(221) # 2 rows, 2 columns, plot 1
plt.plot([1,2,3])
plt.subplot(222) # 2 rows, 2 columns, plot 2
plt.plot([3,1,3])
plt.subplot(223) # 2 rows, 2 columns, plot 3
plt.plot([3,2,1])
plt.subplot(224) # 2 rows, 2 columns, plot 4
plt.plot([1,3,1])
plt.show()
fig.savefig('test.pdf')
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html#matplotlib.pyplot.subplot