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

2024-04-27 02:50:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从多个数据帧中绘制所有参与者的年龄。我想把所有数据帧的年龄绘制成一个图。因此,最终绘图应该包含绘制每个年龄段的数据点。你知道吗

下面是一段代码,我正在尝试,但它给出的是空白的情节。你知道吗

import pandas as pd
import glob
import matplotlib.pyplot as plt
%matplotlib inline

filelist = glob.glob('/Users/kadb/Desktop/participants_tsv_files/*.tsv')
# fig = plt.figure()
ax = fig.add_subplot(111)
# ax.xaxis.set_ticks(df.index)
# ax.xaxis.set_ticklabels(df['g'])
plt.figure()
for file in filelist:
    df = pd.read_table(file)
    if 'age' in df.columns:
        df['age'] = pd.to_numeric(df['age'])
#         df['age'] = df['age'].astype(str).convert_objects(convert_numeric=True)
#         plt.plot(df['age'], 3)
        for index, row in df.iterrows():
            if type(row['age']) is int:
                if row['age'] >= 0:
                    age = row['age']
                    plt.plot(age,10)

tsv文件示例:

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

Tags: 数据inimportdfagetsv绘制plt
1条回答
网友
1楼 · 发布于 2024-04-27 02:50:35

我想这个文件不能正确读入。尝试使用

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

相关问题 更多 >