如何在Matplotlib中展示DataFrame的前5行、后5行及自定义指定行的条形图
实现方案:精准筛选+Matplotlib条形图展示指定条目
当然可以实现这个需求!而且完全能避开全量750行数据带来的冗余问题——核心思路是精准筛选出你需要的三类数据,拼接成一个小型DataFrame后再绘图,这样就不会出现额外空白条目了。
具体步骤&代码示例
假设你的原始DataFrame包含Name(条目名称)和Score(分数,1为最高)两列,咱们可以按以下步骤操作:
- 定义需要展示的条目集合:直接用你给出的明确条目名称,避免排序可能带来的并列值干扰
- 分别筛选三类数据:前5高分、指定条目Beetle、后5低分
- 拼接并清理数据:确保没有NaN值(你已经处理过NaN问题,这里可以再加一层保障)
- 绘制条形图:给不同类别的条形设置区分颜色,添加数值标签让结果更清晰
import pandas as pd import matplotlib.pyplot as plt # 假设你的原始DataFrame名为df # 定义需要展示的三类条目 top_high_score = ['Dog', 'Pig', 'Chicken', 'Cat', 'Fox'] specified_entry = ['Beetle'] top_low_score = ['Tiger', 'Lion', 'Zebra', 'Gorilla', 'Seahorse'] # 精准筛选对应数据 df_top = df[df['Name'].isin(top_high_score)] df_specified = df[df['Name'].isin(specified_entry)] df_bottom = df[df['Name'].isin(top_low_score)] # 拼接成新的DataFrame,重置索引避免混乱 combined_df = pd.concat([df_top, df_specified, df_bottom]).reset_index(drop=True) # 再次确保没有NaN值(防止遗漏) combined_df = combined_df.dropna(subset=['Name', 'Score']) # 绘制条形图 plt.figure(figsize=(12, 6)) # 给三类数据设置不同颜色:前5绿色,指定条目橙色,后5红色 bar_colors = ['#2ecc71']*5 + ['#f39c12'] + ['#e74c3c']*5 bars = plt.bar(combined_df['Name'], combined_df['Score'], color=bar_colors) # 给每个条形添加数值标签 for bar in bars: bar_height = bar.get_height() plt.text(bar.get_x() + bar.get_width()/2, bar_height, f'{bar_height:.2f}', ha='center', va='bottom', fontsize=10) # 设置图表样式 plt.title('Selected Entries Score Comparison', fontsize=14, pad=15) plt.xlabel('Entry Name', fontsize=12) plt.ylabel('Score (1 = Highest)', fontsize=12) plt.xticks(rotation=45, ha='right') plt.tight_layout() # 自动调整布局,避免标签被截断 plt.show()
关于之前的额外条目问题
你提到的图表右侧出现空白条目,确实大概率是因为拼接时带入了含NaN值的行——全量DataFrame里的NaN行在concat时会被保留,导致绘图时出现无内容的空白条形。现在用isin()精准筛选需要的条目,再加上dropna()的双重保障,就完全能避免这个问题了。
内容的提问来源于stack exchange,提问作者Aemonar
相关产品推荐
相关产品推荐

