python - 以一个索引作为 Y 轴,另一个作为 X 轴绘制 pandas 多索引 DataFrame

标签 python pandas matplotlib seaborn multi-index

我有一个在此处采样的多索引数据框:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline

df = pd.read_csv('https://docs.google.com/uc?id=1mjmatO1PVGe8dMXBc4Ukzn5DkkKsbcWY&export=download', index_col=[0,1])

df

enter image description here

我试图绘制此图,以便每一列 ['Var1', 'Var2', 'Var3', 'Var4'] 在一个单独的图中,国家/地区是曲线,y轴Yearx轴

请求的数字将像这个 Ms-Excel 数字

enter image description here

我试着用

来绘制它
f, a = plt.subplots(nrows=2, ncols=2, figsize=(9, 12), dpi= 80)

df.xs('Var1').plot(ax=a[0])
df.xs('Var2').plot(ax=a[1])
df.xs('Var3').plot(x=a[2])
df.xs('Var4').plot(kax=a[3])

但它给出了 KeyError: 'Var1'

我也尝试了以下

f, a = plt.subplots(nrows=2, ncols=2, 
                              figsize=(7, 10), dpi= 80)
for indicator in indicators_list:
    for c, country in enumerate(in_countries):
        ax = df[indicator].plot()
        ax.title.set_text(country + " " + indicator) 

但它返回 3 个空图形和一个包含所有数据的图形 enter image description here

我的试验有什么问题,我该怎么做才能得到我需要的东西?

最佳答案

如果我理解正确的话,你应该首先旋转你的数据框,以便将国家列为列:

In [151]: df.reset_index().pivot('Year','Country','Var1').plot(ax=a[0,0], title='Var1', grid=True)
Out[151]: <matplotlib.axes._subplots.AxesSubplot at 0x127e2320>

In [152]: df.reset_index().pivot('Year','Country','Var2').plot(ax=a[0,1], title='Var2', grid=True)
Out[152]: <matplotlib.axes._subplots.AxesSubplot at 0x12f47b00>

In [153]: df.reset_index().pivot('Year','Country','Var3').plot(ax=a[1,0], title='Var3', grid=True)
Out[153]: <matplotlib.axes._subplots.AxesSubplot at 0x12f84668>

In [154]: df.reset_index().pivot('Year','Country','Var4').plot(ax=a[1,1], title='Var4', grid=True)
Out[154]: <matplotlib.axes._subplots.AxesSubplot at 0x12fbd390>

结果:

enter image description here

关于python - 以一个索引作为 Y 轴,另一个作为 X 轴绘制 pandas 多索引 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48151629/

相关文章:

python - 提取numpy数组中的特定列

python - pandas 根据单元格内容删除行,没有标题

python - 生成负数序列

python - Matplotlib 表 - 为不同的列分配不同的文本对齐方式

matplotlib - 如何为占数据 50% 的条形图着色?

python - tar (Unix) 和 tarfile (Python) 之间的根本区别是什么?

python - 为什么 Python 3.4 给出了大数除法的错误答案,我该如何测试整除性?

python - 如何在python中检查字符串是否为空

python - Pandas :使用 groupby

python - matplotlib 中可能有奥利奥彩色文本吗?