我想使用matplotlib的条形图功能绘制以下形式的数据:
data = {'Room A':
{'Shelf 1':
{'Milk': 10,
'Water': 20},
'Shelf 2':
{'Sugar': 5,
'Honey': 6}
},
'Room B':
{'Shelf 1':
{'Wheat': 4,
'Corn': 7},
'Shelf 2':
{'Chicken': 2,
'Cow': 1}
}
}
Run Code Online (Sandbox Code Playgroud)
条形图应该看起来像这样.应从x轴上的标签可见条形图组.有没有办法用matplotlib做到这一点?
我有一些数据,我使用以下代码操作数据帧:
import pandas as pd
import numpy as np
data = pd.DataFrame([[0,0,0,3,6,5,6,1],[1,1,1,3,4,5,2,0],[2,1,0,3,6,5,6,1],[3,0,0,2,9,4,2,1],[4,0,1,3,4,8,1,1],[5,1,1,3,3,5,9,1],[6,1,0,3,3,5,6,1],[7,0,1,3,4,8,9,1]], columns=["id", "sex", "split", "group0Low", "group0High", "group1Low", "group1High", "trim"])
data
#remove all where trim == 0
trimmed = data[(data.trim == 1)]
trimmed
#create df with columns to be split
columns = ['group0Low', 'group0High', 'group1Low', 'group1High']
to_split = trimmed[columns]
to_split
level_group = np.where(to_split.columns.str.contains('0'), 0, 1)
# output: array([0, 0, 1, 1])
level_low_high = np.where(to_split.columns.str.contains('Low'), 'low', 'high')
# output: array(['low', 'high', 'low', 'high'], dtype='<U4')
multi_level_columns = pd.MultiIndex.from_arrays([level_group, level_low_high], names=['group', 'val'])
to_split.columns …
Run Code Online (Sandbox Code Playgroud) 我有一个带有MultiIndex的pandas DataFrame:
group subgroup obs_1 obs_2
GroupA Elem1 4 0
Elem2 34 2
Elem3 0 10
GroupB Elem4 5 21
Run Code Online (Sandbox Code Playgroud)
等等.正如在这个SO问题中所指出的,这实际上在matplotlib中是可行的,但我宁愿(如果可能的话)使用我已经知道层次结构的事实(感谢MultiIndex).目前正在发生的是索引显示为元组.
这样的事情可能吗?
我一直在努力使用 matlplotlib 在 python 中重新创建这个 Excel 图表:
数据位于数据框中;我正在尝试自动化生成该图的过程。
我尝试过拆开我的数据框、子图,但我还没有成功创建在 Excel 中如此优雅的“区域”索引。我已经成功地在没有这个“区域”索引的情况下绘制了图表,但这并不是我真正想要做的。
这是我的代码:
data = pd.DataFrame(
{
'Factory Zone':
["AMERICAS","APAC","APAC","APAC","APAC","APAC","EMEA","EMEA","EMEA","EMEA"],
'Factory Name':
["Chocolate Factory","Crayon Factory","Jobs Ur Us", "Gibberish US","Lil Grey", "Toys R Us","Food Inc.",
"Pet Shop", "Bonbon Factory","Carrefour"],
'Production Day 1':
[24,1,9,29,92,79,4,90,42,35],
'Production Day 2':
[2,43,17,5,31,89,44,49,34,84]
})
df = pd.DataFrame(data)
print(df)
# Without FactoryZone, it works:
df = df.drop(['Factory Zone'], axis=1)
image = df.plot(kind="bar")
Run Code Online (Sandbox Code Playgroud)
数据如下所示:
Unnamed: 0 FactoryZone Factory Name Production Day 1 Production Day 2
0 1 AMERICAS Chocolate Factory …
Run Code Online (Sandbox Code Playgroud)