使用matplotlib从多个数据帧迭代地绘制单个变量

时间:2017-06-18 11:04:53

标签: python pandas matplotlib plot

我试图绘制来自多个数据帧的所有参与者的年龄。我想将所有数据帧的年龄绘制成一个图。所以最终的情节应该包含绘制每个年龄的数据点。

以下是我正在尝试的一段代码,但它给出的是空白图。

...this class is not key-value compliant for the key label.

示例tsv文件:

popupTitle

1 个答案:

答案 0 :(得分:1)

我猜这个文件无法正确读取。尝试使用

pd.read_table(f, delim_whitespace=True)

您在创建图形之前创建了子图。这需要逆转。

接下来,如果type(row['age'])不是int怎么办?

如果您可以确保row['age']包含int,则下一个问题是您尝试将单个点绘制为线图。

使用

plt.plot(age,10, marker="o")

使得该点附有标记,可以显示。

总的来说,代码可以变得更加紧凑;所以以下内容应该能满足您的需求。

u = u"""participant_id  gender  age physioSampling  restAcquisiotion
sub-01  M   26  50  after_cuedSGT
sub-02  M   21  50  after_cuedSGT
sub-03  M   22  50  after_cuedSGT
sub-04  M   23  50  after_cuedSGT
sub-05  M   21  50  before_cuedSGT
sub-06  M   19  50  before_cuedSGT
sub-07  F   18  50  before_cuedSGT
sub-08  F   21  50  before_cuedSGT
sub-09  M   20  40-60   before_cuedSGT
sub-10  F   21  50  before_cuedSGT
sub-11  F   20  50  before_cuedSGT
sub-12  M   21  50  before_cuedSGT
sub-13  F   31  50-60   before_cuedSGT"""

import io
import pandas as pd
import glob
import matplotlib.pyplot as plt


filelist = [io.StringIO(u)]

fig, ax = plt.subplots()

for f in filelist:
    df = pd.read_table(f, delim_whitespace=True)
    if 'age' in df.columns:
        #df = df[df["age"] != "n/a"] # remove n/a values or
        df = df[~df["age"].isin(["n/a"])]
        plt.plot(df['age'], [3]*len(df), marker="o", ls="")

plt.show()

enter image description here