【问题标题】:python plot grouped bar graphpython plot 分组条形图
【发布时间】:2018-07-24 15:23:31
【问题描述】:

我有一个如下所示的 3 列数据

 clm1                       clm2     clm3
 |["shared","connect"]       13297  |aaaa|
 |["stopped","failed]        25002  |aaaa|
 |["success","obtained"]     11189  |aaaa|
 |["shared","connect"]       16770  |bbbb|
 |["stopped","failed]        81777  |bbbb|
 |["success","obtained"]     9555   |bbbb|

我想要下面的python条形图,我可以编写简单的图表,但无法编写可以对 clm3 进行分组和绘图的逻辑

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这里的主要问题是matplotlib认为你所有的分类数据“A”代表同一个类别,所以它把它们绘制在“A”的同一个地方。我们必须发明一个额外的类别来区分所有这些“A”值。例如,我们可以使用cumcount() 来执行此操作,它将所有值“A”从 0 编号到 n。一个例子是:

    from matplotlib import pyplot as plt
    import pandas as pd
    
    #create toy dataframe
    #this part you should have included in your question
    #as a Minimal, Complete, and Verifiable example
    np.random.seed(1234)
    df = pd.DataFrame({"cat": ["A", "B", "C", "C", "B", "C", "A"], "val": np.random.randint(1, 100, 7)})
    
    #add column for multiple cat values and rearrange dataframe
    df["cols"] = df.groupby("cat").cumcount()
    df1 = df.pivot(index = "cat", columns = "cols", values = "val")
    print(df1)
    
    #plot this table
    df1.plot.bar(color = "blue", edgecolor = "white")
    plt.legend().set_visible(False)
    plt.xticks(rotation = 0)
    plt.show()
    

    示例数据框:

    cols     0     1     2
    cat                   
    A     48.0  16.0   NaN
    B     84.0  77.0   NaN
    C     39.0  54.0  25.0
    

    示例图:

    编辑: 我只是注意到,在你的情况下它更容易,因为虽然你的问题中从未提到过,但你可能想要作为类别“clm1”。因此,您可以简化程序:

    from matplotlib import pyplot as plt
    import pandas as pd
    
    #create toy dataframe
    np.random.seed(1234)
    df = pd.DataFrame({"clm1": ["X", "Y", "Z", "X", "Y", "Z"], "clm2": np.random.randint(1, 100, 6), "clm3": ["A", "A", "A", "B", "B", "B"]})
    
    #rearrange dataframe and plot
    df.pivot(index = "clm3", columns = "clm1", values = "clm2").plot.bar(edgecolor = "white")
    plt.xticks(rotation = 0)
    plt.show()
    

    样本输出:

    【讨论】:

      猜你喜欢
      • 2016-03-21
      • 1970-01-01
      • 2011-03-01
      • 2019-09-05
      • 2020-03-25
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多