【发布时间】:2019-10-06 02:59:01
【问题描述】:
我有一些临床数据,其中包含多个受试者多次就诊的值。我创建了一个脚本来循环并为每个主题创建一个包含每次访问值的图。现在,我需要为每个主题图添加数据:
-
对于每个主题,添加一个新标记(星号)以仅标识基线值(bcva_OS 和 bcva_OD)。我只能让它显示所有值的标记。如何仅对基线进行子集化?请参阅代码中的注释。如果我使用,我会收到语法错误:
plt.plot_date(sub_df['visit_date'] if sub_df[sub_df.visit_label == 'Visit 2 - Baseline'], 对于每个主题,我如何添加全新的数据类型,以便将两种数据类型叠加在每个主题的图上?我想我可以只用一个主题的数据来做到这一点,但又是循环......
示例代码:
for subject, sub_df in new_od_df.groupby(by='subject'):
# Plot fellow eye
plt.plot(sub_df['visit_date'], sub_df['bcva_OS'], marker='^',
label='OS (fellow) ', color=sns.xkcd_rgb['pale red'])
# Plot treated eye
plt.plot(sub_df['visit_date'], sub_df['bcva_OD'], marker='o',
label='OD (treated) ', color=sns.xkcd_rgb['denim blue'])
# Trying to plot only the baseline values
#plt.plot_date(sub_df['visit_date'] if sub_df[sub_df.visit_label == 'Visit 2 - Baseline'],
# Plot fellow eye
plt.plot_date(sub_df['visit_date'], sub_df['bcva_OS'],
marker='*', markersize=10,
label='BL (fellow) ', color=sns.xkcd_rgb['light pink'])
# Plot treated eye
plt.plot_date(sub_df['visit_date'], sub_df['bcva_OD'],
marker='*', markersize=10,
label='BL (treated) ', color=sns.xkcd_rgb['baby blue'])
# Legend the old way
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)
# Display each chart separately
plt.show()
样本数据:
subject treated_eye visit_label visit_date bcva_OD bcva_OS refract_OD refract_OS
index
108 1101 OD Visit 1 - Screening 2016-01-07 27.0 41.0 + 5 + 0.75 X 27 + 5 + 1.75 X 45
115 1101 OD Visit 2 - Baseline 2016-01-25 35.0 41.0 + 5 + 0.75 X 27 + 5.5 + 1.75 X 40
120 1101 OD Baseline - VA Session 2 2016-01-25 35.0 41.0 + 5 + 0.75 X 27 + 5.5 + 1.75 X 40
125 1101 OD Visit 4 - Day 1 2016-02-02 32.0 42.0 + 5 + 0.75 X 27 + 5 + 1.75 X 30
123 1101 OD Visit 5 - Day 7 2016-02-08 40.0 43.0 + 5 + 0.75 X 28 + 5 + 1.75 X 30
111 1101 OD Visit 6 - Day 14 2016-02-16 33.0 44.0 + 5 + 0.75 X 27 + 5 + 1.75 X 40
124 1101 OD Unscheduled 2016-02-24 37.0 44.0 + 4.5 + 1.25 X 30 + 5 + 1.75 X 40
118 1101 OD Visit 7 - Month 1 2016-02-29 37.0 40.0 + 4.5 + 1.25 X 30 + 5 + 1.75 X 43
样图:
【问题讨论】:
-
欢迎来到 SO!与其将示例数据发布为图像,不如将它们发布为代码以便轻松复制?这样可以更轻松地回答您的问题。
-
感谢您的提示。我更新了数据,但不确定我的更新是否有帮助。
-
这肯定更好 - 但最好是如果你可以把它写成以下形式:
df = pd.DataFrame( ... )- 这样你就可以确保人们完全按照预期使用你的样本数据。 -
我认为你应该能够绘制像
plt.plot_date(sub_df['visit_date'][ mask ])这样的掩码值mask=(sub_df[sub_df.visit_label == 'Visit 2 - Baseline']) -
@Asmus,这会导致 'TypeError: Indexing a Series with DataFrame is not supported, use the appropriate DataFrame column
标签: python pandas loops matplotlib