关于使用Python绘制年龄>0.5岁人群图表的技术咨询
嘿,我来帮你搞定绘制年龄大于0.5岁人群图表的需求!先把你的DataFrame代码补全,再一步步筛选数据、完成绘图:
第一步:补全并验证你的DataFrame
首先把你没写完的DataFrame代码补全,确保数据能正确加载:
import pandas as pd data = { 'age': [0.62,0.84,0.78,0.80,0.70,0.25,0.32,0.86,0.75], 'gender': [1,0,0,0,1,0,0,1,0], 'LOS': [0.11,0.37,0.23,-0.02,0.19,0.27,0.37,0.31,0.21], 'WBS': [9.42,4.40,6.80,9.30,5.30,5.90,3.10,4.10,12.07], 'HB': [22.44,10.40,15.60,15.10,11.30,10.60,12.50,10.40,14.10], 'Nothrophil': [70.43,88.40,76.50,87,82,87.59,15.40,77,88] } df = pd.DataFrame(data)
第二步:筛选年龄大于0.5岁的人群数据
用布尔索引快速筛选符合条件的行,这一步很关键:
# 筛选age > 0.5的数据 df_filtered = df[df['age'] > 0.5] # 可以打印看看筛选结果 print(df_filtered)
第三步:绘制常见图表示例
下面给你几个实用的绘图例子,你可以根据自己的需求调整:
示例1:性别分布柱状图(用matplotlib)
如果想看看筛选后人群的性别占比,试试这个:
import matplotlib.pyplot as plt # 统计性别数量 gender_counts = df_filtered['gender'].value_counts() # 设置图表 plt.figure(figsize=(6,4)) gender_counts.plot(kind='bar', color=['#1f77b4', '#ff7f0e']) plt.title('Gender Distribution (Age > 0.5)') plt.xlabel('Gender (0=Female, 1=Male)') plt.ylabel('Count') plt.xticks(rotation=0) # 让x轴标签不旋转 plt.show()
示例2:住院时长(LOS)与白细胞计数(WBS)的散点图(用seaborn)
想探索两个指标的相关性?用seaborn画散点图更美观:
import seaborn as sns plt.figure(figsize=(8,5)) sns.scatterplot(data=df_filtered, x='WBS', y='LOS', hue='gender', size='age', alpha=0.7) plt.title('LOS vs WBS (Age > 0.5)') plt.xlabel('White Blood Cell Count (WBS)') plt.ylabel('Length of Stay (LOS)') plt.legend(title='Gender') plt.show()
示例3:血常规指标的箱线图
对比不同性别下HB和中性粒细胞(Nothrophil)的分布:
# 把数据转换为长格式,方便画箱线图 df_melted = df_filtered.melt(id_vars='gender', value_vars=['HB', 'Nothrophil'], var_name='Indicator', value_name='Value') plt.figure(figsize=(10,6)) sns.boxplot(data=df_melted, x='Indicator', y='Value', hue='gender') plt.title('Blood Test Indicators by Gender (Age > 0.5)') plt.ylabel('Measurement Value') plt.show()
这些代码都可以直接运行,你还可以根据需求调整颜色、标题、图表类型(比如折线图、饼图)哦!
内容的提问来源于stack exchange,提问作者Elnaz
相关产品推荐
相关产品推荐

