简体   繁体   English

绘制熊猫多索引DataFrame,其中一个索引作为Y轴,另一个作为X轴

[英]Plotting pandas multi-index DataFrame with one index as Y-axis and other as X-axis

I have a multi-index dataframe that is sampled here: 我有一个在这里采样的多索引数据框:

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

在此处输入图片说明

I tried to plot this so that each column ['Var1', 'Var2', 'Var3', 'Var4'] in a separate figure, the Country is a curve, and y-axis , and the Year is the x-axis 我试图对此进行绘制,以使每个列['Var1', 'Var2', 'Var3', 'Var4']在单独的图中,“ Country是曲线,而y-axis ,而Yearx-axis

the requested figure would be like this Ms-Excel figure 要求的数字将类似于Excel的数字

在此处输入图片说明

I tried to plot it using 我试图使用绘制它

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])

but it gives KeyError: 'Var1' 但它给出了KeyError: 'Var1'

I also tried the following 我也尝试了以下

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) 

but it returns 3 empty figures and one figure with all the data in it 但它会返回3个空图和一个包含所有数据的图 在此处输入图片说明

What is wrong with my trials and What can I do to get what I need? 我的审判有什么问题,我该怎么做才能获得所需的东西?

If I understand correctly you should first pivot your dataframe in order to have countries as columns: 如果我正确理解,则应首先旋转数据框,以将国家/地区作为列:

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>

Result: 结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM