如何在Python中过滤数据以绘制符合条件的条形图?
筛选后数据可视化方案
直接把筛选逻辑和可视化代码结合即可,下面是两种常用实现方式:
方式一:使用Matplotlib
# 1. 筛选符合条件的数据 filtered_df = df[df['Degree Status'].str.contains('HS-grad') & df['Earnings'].str.contains('<=50K')] # 2. 统计各Job-Type的出现频次 job_type_counts = filtered_df['Job-Type'].value_counts() # 3. 绘制条形图 import matplotlib.pyplot as plt # 设置画布大小 plt.figure(figsize=(12, 6)) # 绘制条形图 job_type_counts.plot(kind='bar') # 添加标题和轴标签 plt.title('Job Type Distribution (HS-grad, Earnings <=50K)') plt.xlabel('Job Type') plt.ylabel('Number of Individuals') # 旋转x轴标签避免重叠 plt.xticks(rotation=45, ha='right') # 自动调整布局防止标签截断 plt.tight_layout() # 显示图形 plt.show()
方式二:使用Seaborn(更美观的统计图表)
# 1. 筛选符合条件的数据 filtered_df = df[df['Degree Status'].str.contains('HS-grad') & df['Earnings'].str.contains('<=50K')] # 2. 绘制条形图 import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(12, 6)) # 按频次排序显示Job-Type sns.countplot(data=filtered_df, x='Job-Type', order=filtered_df['Job-Type'].value_counts().index) plt.title('Job Type Distribution (HS-grad, Earnings <=50K)') plt.xlabel('Job Type') plt.ylabel('Number of Individuals') plt.xticks(rotation=45, ha='right') plt.tight_layout() plt.show()
注意点
- 如果
Degree Status和Earnings列是精确匹配场景,可把str.contains替换为==(比如df['Degree Status'] == 'HS-grad'),筛选精度更高。 - 可调整
figsize的数值改变图表尺寸,适配不同展示需求。
内容的提问来源于stack exchange,提问作者xyzpy159
相关产品推荐
相关产品推荐

