Python 使用多索引绘制熊猫图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25386870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:08:40  来源:igfitidea点击:

Pandas Plotting with Multi-Index

pythonmatplotlibpandasmulti-index

提问by Reustonium

After performing a groupby.sum()on a DataFrameI'm having some trouble trying to create my intended plot.

在 agroupby.sum()上执行 a 后,DataFrame我在尝试创建我想要的情节时遇到了一些麻烦。

grouped dataframe with multi-index

具有多索引的分组数据框

How can I create a subplot (kind='bar') for each Code, where the x-axis is the Monthand the bars are ColAand ColB?

如何kind='bar'为每个创建子图 ( ) Code,其中 x 轴是 the Month,条形图是ColAand ColB

采纳答案by Reustonium

I found the unstack(level) method to work perfectly, which has the added benefit of not needing a priori knowledge about how many Codes there are.

我发现 unstack(level) 方法可以完美地工作,它的另一个好处是不需要关于有多少代码的先验知识。

df.unstack(level=0).plot(kind='bar', subplots=True)

回答by segmentationfault

Using the following DataFrame ...

使用以下数据帧...

DataFrame

数据框

# using pandas version 0.14.1
from pandas import DataFrame
import pandas as pd
import matplotlib.pyplot as plt

data = {'ColB': {('A', 4): 3.0,
('C', 2): 0.0,
('B', 4): 51.0,
('B', 1): 0.0,
('C', 3): 0.0,
('B', 2): 7.0,
('Code', 'Month'): '',
('A', 3): 5.0,
('C', 1): 0.0,
('C', 4): 0.0,
('B', 3): 12.0},
'ColA': {('A', 4): 66.0,
('C', 2): 5.0,
('B', 4): 125.0,
('B', 1): 5.0,
('C', 3): 41.0,
('B', 2): 52.0,
('Code', 'Month'): '',
('A', 3): 22.0,
('C', 1): 14.0,
('C', 4): 51.0,
('B', 3): 122.0}}

df = DataFrame(data)

... you can plot the following (using cross-section):

...您可以绘制以下内容(使用横截面):

f, a = plt.subplots(3,1)
df.xs('A').plot(kind='bar',ax=a[0])
df.xs('B').plot(kind='bar',ax=a[1])
df.xs('C').plot(kind='bar',ax=a[2])

enter image description here

在此处输入图片说明

One for A, one for B and one for C, x-axis: 'Month', the bars are ColA and ColB. Maybe this is what you are looking for.

一个用于 A,一个用于 B,一个用于 C,x 轴:“月”,条形是 ColA 和 ColB。也许这就是你正在寻找的。