在熊猫条形图中按列分组

时间:2020-09-30 13:56:20

标签: python pandas matplotlib

我正在我的数据框对象上运行groupby实用程序功能,此后我想生成一个条形图。我希望每个旁边都有两个酒吧,即每周一个:

代码如下:

        df3 = (
            self.df
                .groupby(by=['week', 'type'], dropna=False)
                .sum()
                .unstack()
        )

产生的结果:

type                              type1       type2
week                                     
1                             81.44            NaN
2                            591.30          1900.0
3                             91.10            NaN
4                            146.48          11000.0
5                            218.76            NaN

我现在正在努力通过调用以下方法来绘制它:

axs.bar(numpy.arange(5, 1), df3)

其输出“ ValueError:形状不匹配:对象无法广播为单个形状”。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

您还需要为.bar() method提供单列(即数据框列)的高度。

import pandas as pd, numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame([
        [1, 'type1', 81.44], 
        [2, 'type1', 591.3], 
        [2, 'type2', 1900], 
        [3, 'type1', 91.1], 
        [4, 'type1',146.48], 
        [4, 'type2', 11000], 
        [5, 'type1', 218.76]
], columns=['week', 'type', 'value'])

df3 = df.groupby(by=['week', 'type'])\
                .sum()\
                .unstack()

# Create plot

# Define the variables to display
bars = [df3.value.type1, df3.value.type2]

# Create the axes
axs = plt.subplot(111)            

# Plot 'type1'
axs.bar(x = np.arange(1, 1 + len(bars[0])) - .15, height = bars[0], width = .2, data = df3)
# Plot 'type2'
axs.bar(x = np.arange(1,1 + len(bars[1])) + .15, height = bars[1], width = .2, data = df3)

enter image description here

答案 1 :(得分:0)

这将创建您想要的内容:

// First day of the month.
$first_day = strtotime( date( 'Y-m-01' ) );
// Last day of the month.
$last_day = strtotime( date( 'Y-m-t' ) );

$args = array(
    'fields'     => 'ID',
    'role'       => 'customer',
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'course_%_access_from',
            'value' => array( $first_day, $last_day ),
            'type' => 'numeric',
            'compare' => 'BETWEEN'
        ),
    )
);
$users = get_users($args);

enter image description here

答案 2 :(得分:0)

将选项ax传递给df3.plot怎么样?

df3.plot.bar(ax=axs)
相关问题