两个pandas数据框的分组条形图

时间:2017-03-01 12:54:10

标签: python pandas dataframe

我有两个包含不同值但结构相同的数据框:

df1 =

         0         1         2         3         4 
D  0.003073  0.014888  0.155815  0.826224       NaN
E  0.000568  0.000435  0.000967  0.002956  0.067249  

df2 =

     0         1         2         3         4
D  0.746689  0.185769  0.060107  0.007435       NaN   
E  0.764552  0.000000  0.070288  0.101148  0.053499

我想在单个分组条形图中绘制两个数据框。此外,每一行(索引)应该是一个子图。

对于其中一个直接使用熊猫的人来说,这很容易实现:

df1.T.plot(kind="bar", subplots=True, layout=(2,1), width=0.7, figsize=(10,10), sharey=True)

我尝试使用

加入他们
pd.concat([df1, df2], axis=1)

会产生新的数据框:

         0         1         2         3         4         0         1         2         3         4
D  0.003073  0.014888  0.155815  0.826224       NaN  0.746689  0.185769  0.060107  0.007435       NaN
E  0.000568  0.000435  0.000967  0.002956  0.067249  0.764552  0.000000  0.070288  0.101148  0.053499

但是,使用上述方法绘制数据框不会对每列的条形图进行分组,而是将它们分开处理。对于每个子图,这导致x轴具有按列的顺序重复的刻度,例如, 0,1,2,3,4,0,1,2,3,4

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

数据的组织方式尚不清楚。大熊猫和海鸟通常期待tidy datasets。因为你在绘图之前转移数据我假设你有两个变量(A和B)和四个观察值(例如测量值)

df4 = pd.concat([df1.T, df2.T], axis=0, ignore_index=False)
df4['col'] = (len(df1.T)*(0,) + len(df2.T)*(1,))
df4.reset_index(inplace=True)
df4

enter image description here

也许这接近你想要的东西:

sns.factorplot(x='index', y='A', hue='col', kind='bar', data=df4)

enter image description here

使用seaborns facet grid可以方便地绘图:

#include <stdio.h>
int sum(int i);
int main(void)
{
    int num;
    printf("Enter an integer greater than zero, (q to quit): ");
    while (scanf("%d",&num)==1)
    {
        //Checks if the entered integer is positive
        if (num<0)
            printf("Please enter a positive integer.\n");
        //Prints out the sum of the entered integer
        else
            printf("Sum(%d) = %d\n",num, sum(num));
        printf("Enter an integer greater than zero, (q to quit): ");
    }
    printf("Bye.");
    return 0;
}
//Calculates the sum of inputted value
int sum(int i)
{
    int answer;
    //Runs until the sum is added in reverse order
    if (i>0)
        answer=i+(sum(i-1));
    else
        answer=0;
    return answer;
}

enter image description here

相关问题