如何使用 Python 中的 Pandas 绘制条形图以比较具有多个变量的多个系统

How to plot bar chart to compare multiple systems with multiple variables using Pandas in Python

我正在使用 Pandas 进行一些基本数据分析,但在绘制数据时遇到了问题。我有多个系统的数据,每个系统都有排名位置 (1-10)。在每个排名位置中,都有 A、C 和 F 等级,以及百分比。我想为每个系统制作一个图表,其中 x 轴包含排名,y 轴包含成绩百分比。这是我的数据示例:

{
  "System1": {
      "1": {
             "A": 0.5,
             "C": 0.3,
             "F": 0.1
           },
      "2": {
             "A": 0.3,
             "C": 0.3,
             "F": 0.4
           },
      ...,
      "10": {
              "A": 0.1,
              "C": 0.3,
              "F": 0.6
            }
   },
   "System2": {
       "1": {
              ...
            },
       ...,
       "10": {
              ...
        }
   }
}

我想生成如下所示的图表:

我已使用 pd.DataFrame.from_dict(ranked_grades) 将我的数据加载到数据框中,但我无法让 Pandas 处理我的数据的嵌套结构。加载后我的数据框如下所示:

                                              System1                                           System2                                
1   {'C': 0.35377358490566035, 'F': 0.132075471698...  {'C': 0.3696682464454976, 'F': 0.1611374407582...  
2   {'C': 0.33490566037735847, 'F': 0.372641509433...  {'C': 0.3459715639810427, 'F': 0.2890995260663...  
3   {'C': 0.330188679245283, 'F': 0.41037735849056...  {'C': 0.3080568720379147, 'F': 0.4502369668246...  
4   {'C': 0.2783018867924528, 'F': 0.5235849056603...  {'C': 0.3175355450236967, 'F': 0.4739336492890... 
...
10  {'C': 0.2830188679245283, 'F': 0.5943396226415...  {'C': 0.24170616113744076, 'F': 0.630331753554... 

from_dict 方法不需要嵌套的字典。因此,您需要以这种方式循环读取数据。

dfs = []
for key in sorted(ranked_grades):
    dfs.append(pd.DataFrame.from_dict(ranked_grades[key]))

然后,用 concat

将它们推到一起
data = pd.concat(dfs, keys=sorted(ranked_grades))

现在你应该有一个可以使用的数据结构了。

我在这里学到了很多东西。如果我发现更多,我可能会更新这个答案。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

d = {
    k0: {
        k1: {
            k2: np.random.randint(0, 10) / 10 for k2 in list('ACF')
        } for k1 in range(1, 11)
    } for k0 in ['System1', 'System2']
}

df = pd.Panel(d).to_frame().rename_axis([None, None]).T.stack()
fig, axes = plt.subplots(2, 1, figsize=(6, 4), sharex=True)
for i, (name, group) in enumerate(df.groupby(level=0)):
    group.xs(name).sort_index().plot.bar(ax=axes[i], ylim=[0, 1])
    axes[i].set_title(name, rotation=270, position=(1.05, .55),
                      backgroundcolor='gray')

axes[0].legend(bbox_to_anchor=(1.1, .2), loc=2, borderaxespad=0.)
axes[1].legend().remove()

plt.subplots_adjust(hspace=0.1)