如何基于给定pandas DataFrame绘制分3组的多柱状图展示语言比值
实现方案
核心逻辑
- 先按语言维度计算每组(numeric/text/both)的分子/分母比值
- 基于计算后的比值矩阵绘制分组柱状图,同分组下三个语言的柱子横向排列,用不同颜色区分
完整可运行代码
import pandas as pd import matplotlib.pyplot as plt import numpy as np # 构造模拟DataFrame data = {'numerator_en':[11, 113, 53], 'denominator_en':[91, 982, 298], 'numerator_fr':[6, 232, 58], 'denominator_fr':[63, 1278, 389], 'numerator_th':[14, 652, 231], 'denominator_th':[416, 3835, 1437], } dummy_df = pd.DataFrame(data, index = ['numeric', 'text', 'both']) # 计算各语言对应比值 ratio_df = pd.DataFrame({ '英语': dummy_df['numerator_en'] / dummy_df['denominator_en'], '法语': dummy_df['numerator_fr'] / dummy_df['denominator_fr'], '泰语': dummy_df['numerator_th'] / dummy_df['denominator_th'] }) # 绘制分组柱状图 x = np.arange(len(ratio_df.index)) # 分组位置 width = 0.25 # 单根柱子宽度 fig, ax = plt.subplots(figsize=(8,5)) rects1 = ax.bar(x - width, ratio_df['英语'], width, label='英语', color='#1f77b4') rects2 = ax.bar(x, ratio_df['法语'], width, label='法语', color='#ff7f0e') rects3 = ax.bar(x + width, ratio_df['泰语'], width, label='泰语', color='#2ca02c') # 图表配置 ax.set_ylabel('分子/分母 比值') ax.set_xticks(x, ratio_df.index) ax.legend() # 可选:在柱子顶部显示数值,不需要可以删除以下三行 ax.bar_label(rects1, fmt='%.3f', padding=3) ax.bar_label(rects2, fmt='%.3f', padding=3) ax.bar_label(rects3, fmt='%.3f', padding=3) fig.tight_layout() plt.show()
运行代码即可输出符合要求的分组柱状图,你可以根据需求自行调整颜色、图表尺寸、数值精度等参数。
内容的提问来源于stack exchange,提问作者Exa
相关产品推荐
相关产品推荐

