Plot multiple stacked bar in the same figure

后端 未结 2 1004
旧时难觅i
旧时难觅i 2021-01-03 15:01

i would like to multiple stacked bar in the same plot. This is my code:

    file_to_plot = file_to_plot.set_index([\'user\'])
    fig, ax = plt.subplots()
           


        
相关标签:
2条回答
  • 2021-01-03 15:41

    I thought this would be straightforward. Hopefully someone else will chime in with a better solution. What I did was to take the diff's of the columns and run a stacked chart.

    df = pd.DataFrame(dict(
        A=[1, 2, 3, 4],
        B=[2, 3, 4, 5],
        C=[3, 4, 5, 6]
    ))
    
    df.diff(axis=1).fillna(df).astype(df.dtypes).plot.bar(stacked=True)
    


    For comparison

    fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
    
    df.plot.bar(ax=axes[0])
    df.diff(axis=1).fillna(df).astype(df.dtypes).plot.bar(ax=axes[1], stacked=True)
    

    0 讨论(0)
  • 2021-01-03 15:46

    This should work the way you want:

    import pandas as pd
    
    df = pd.DataFrame(dict(
        A=[1, 2, 3, 4],
        B=[2, 3, 4, 5],
        C=[3, 4, 5, 6],
        D=[4, 5, 6, 7]))
    
    import matplotlib.pyplot as plt
    %matplotlib inline
    fig = plt.figure(figsize=(20, 10))
    
    ab_bar_list = [plt.bar([0, 1, 2, 3], df.B, align='edge', width= 0.2),
                   plt.bar([0, 1, 2, 3], df.A, align='edge', width= 0.2)]
    
    cd_bar_list = [plt.bar([0, 1, 2, 3], df.D, align='edge',width= -0.2),
                   plt.bar([0, 1, 2, 3], df.C, align='edge',width= -0.2)]
    

    Just keep in mind, the width value for one group must be positive, and negative for the second one. Use align by edge as well.
    You have to place the bar with the biggest values before the bar with the lowest values, and if you want the bars to appear stacked above one another rather than one in front of another, change df.B and df.D to df.B + df.A and df.D + df.C, respectively. If there's no apparent or consisting pattern, use the align by edge and width method with the one suggested by @piRSquared.
    Another alternative would be to access each value from a green bar and compare it to the corresponding value from the red bar, and plot accordingly (too much unnecessary work in this one).

    0 讨论(0)
提交回复
热议问题