用三组绘制多个条形图,同时划分两列

时间:2021-06-08 20:46:43

标签: python pandas dataframe matplotlib

我有这个虚拟 df:

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'])

看起来像这样: enter image description here

目标是创建这样一个情节: enter image description here

请注意,英语、法语和泰语的颜色应该不同 - 没有图片中的花哨。

在此,对于分为数字、文本和两者的所有语言,y 轴等于 numerator_xx / denominator_xx。
例如,数字将是行数字:numerator_en/denominator_en 和 numerator_fr/denominator_fr 等等...

英语 = _en 法语 = _fr 泰语 = _th

2 个答案:

答案 0 :(得分:2)

尝试使用 str.split 创建多索引,然后将 numerator 除以 denominator

dummy_df.columns = dummy_df.columns.str.split('_', expand=True)
dummy_df = dummy_df['numerator'] / dummy_df['denominator']

dummy_df

               en        fr        th
both     0.177852  0.149100  0.160752
numeric  0.120879  0.095238  0.033654
text     0.115071  0.181534  0.170013

然后plot照常:

dummy_df.plot(kind='bar', rot=0)
plt.show()

plot


完整的工作示例:

import pandas as pd
from matplotlib import pyplot as plt

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'])

dummy_df.columns = dummy_df.columns.str.split('_', expand=True)
dummy_df = dummy_df['numerator'] / dummy_df['denominator']

dummy_df.plot(kind='bar', rot=0)
plt.show()

答案 1 :(得分:2)

您可以将 groupby 与 axis=1 结合使用,以根据 en/fr/th 创建组。 然后您可以评估每个组的 numerator/denominator。 最后,您可以使用 .plot(kind ='bar') 绘制条形图。

(
    df.groupby(df.columns.map(lambda x: x.split('_')[1]), axis=1)
    .apply(lambda x: x.iloc[:, 0].div(x.iloc[:, 1]))
    .plot(kind='bar')
)

输出:

enter image description here