我有一个在此处采样的多索引数据框:
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
我试图绘制此图,以便每一列 ['Var1', 'Var2', 'Var3', 'Var4']
在一个单独的图中,国家/地区
是曲线,y轴
,Year
是x轴
请求的数字将像这个 Ms-Excel 数字
我试着用
来绘制它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)
我的试验有什么问题,我该怎么做才能得到我需要的东西?
最佳答案
如果我理解正确的话,你应该首先旋转你的数据框,以便将国家列为列:
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>
结果:
关于python - 以一个索引作为 Y 轴,另一个作为 X 轴绘制 pandas 多索引 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48151629/