我正在寻找一种基于一个类别在同一视图中生成单个绘图的编程方式。
[示例]想象以下DF:
country agg_meat_consumption_tons month
US 300 JAN
BR 100 JAN
IN 10 JAN
RU 200 JAN
US 400 FEB
BR 300 FEB
IN 5 FEB
RU 240 FEB
US 150 MAR
BR 90 MAR
IN 10 MAR
RU 400 MAR
如果我想生成一个图表来说明每个国家/地区的消费数量,我知道我可以写下这样的内容:
df_pv = df.pivot_table(
values='agg_meat_consumption_tons',
index='month',
columns='country')
但是,我想为每个国家/地区生成单独的图表,并在同一视图中打印所有结果。基本上,一些程序化的东西可以让我避免为每个国家写这样的东西:
df_us = df[df['country']=='US']
df_us_pv = df_us.pivot_table(
values='agg_meat_consumption_tons',
index='month',
columns='country')
提前致谢!
答案 0 :(得分:2)
更新了我对你下面评论的回答 - 我对matplotlib不是很了不起,但这会让你获得90%的回报。其他任何人请随时添加/编辑。
import datetime
import matplotlib.pyplot as plt
# %matplotlib inline
df
Out[12]:
country consump veg_amt month
0 US 300 94 JAN
1 BR 100 38 JAN
2 IN 10 40 JAN
3 RU 200 97 JAN
4 US 400 73 FEB
.. ... ... ... ...
7 RU 240 20 FEB
8 US 150 72 MAR
9 BR 90 39 MAR
10 IN 10 46 MAR
11 RU 400 79 MAR
# Map month text values to numeric for sorting, remap later
months = ({(datetime.datetime(2000,i,1).strftime("%b")).upper():
i for i in range(1, 13)})
inv_month = {v: k for k, v in months.items()}
ptable = df.pivot_table(
values=['consump', 'veg_amt'],
index=df.month.map(months),
columns='country')
ptable = ptable.swaplevel(axis=1).sort_index(axis=1)
ptable.index = Series(ptable.index).map(inv_month)
ptable
Out[86]:
country BR IN RU US
consump veg_amt consump veg_amt consump veg_amt consump veg_amt
month
JAN 100 38 10 40 200 97 300 94
FEB 300 54 5 74 240 20 400 73
MAR 90 39 10 46 400 79 150 72
cols = ptable.columns.get_level_values(0).unique()
num_countries = len(df.country.unique())
fig, axes = plt.subplots(num_countries, sharex=True)
for col, num in zip(cols, range(num_countries)):
ptable.xs(col, axis=1).plot(ax=axes[num])
答案 1 :(得分:1)
# Turning that column to a list
country = df['country'].tolist()
for country in country:
df_us = df[df['country']==str(country)]
df_us_pv = df_us.pivot_table(
values='agg_meat_consumption_tons',
index='month',
columns='country')
# just printing for output
print(df_us_pv)