【问题标题】:Plotting pandas dataframe with two groups用两组绘制熊猫数据框
【发布时间】:2017-06-15 00:20:40
【问题描述】:

我正在使用 Pandas 和 matplotlib 尝试从 tableau 复制此图:

到目前为止,我有这个代码:

group = df.groupby(["Region","Rep"]).sum()
total_price = group["Total Price"].groupby(level=0, group_keys=False)
total_price.nlargest(5).plot(kind="bar")

生成此图:

它正确地对数据进行分组,但是否可以像 Tableau 显示的那样进行分组?

【问题讨论】:

    标签: python pandas matplotlib tableau-api


    【解决方案1】:

    您可以使用各自的 matplotlib 方法(ax.textax.axhline)创建一些线条和标签。

    import pandas as pd
    import numpy as np; np.random.seed(5)
    import matplotlib.pyplot as plt
    
    a = ["West"]*25+ ["Central"]*10+ ["East"]*10
    b = ["Mattz","McDon","Jeffs","Warf","Utter"]*5 + ["Susanne","Lokomop"]*5 + ["Richie","Florence"]*5
    c = np.random.randint(5,55, size=len(a))
    df=pd.DataFrame({"Region":a, "Rep":b, "Total Price":c})
    
    
    group = df.groupby(["Region","Rep"]).sum()
    total_price = group["Total Price"].groupby(level=0, group_keys=False)
    
    gtp = total_price.nlargest(5)
    ax = gtp.plot(kind="bar")
    
    #draw lines and titles
    count = gtp.groupby("Region").count()
    cum = np.cumsum(count)
    for i in range(len(count)):
        title = count.index.values[i]
        ax.axvline(cum[i]-.5, lw=0.8, color="k")
        ax.text(cum[i]-(count[i]+1)/2., 1.02, title, ha="center",
                transform=ax.get_xaxis_transform())
    
    # shorten xticklabels
    ax.set_xticklabels([l.get_text().split(", ")[1][:-1] for l in ax.get_xticklabels()])
    
    plt.show()
    

    【讨论】:

    • 这太棒了!谢谢!现在要真正经历并了解它在做什么。 :)
    猜你喜欢
    • 2017-06-09
    • 2019-12-14
    • 2017-05-28
    • 2022-01-08
    • 2016-01-07
    • 2021-10-16
    • 1970-01-01
    • 2017-10-10
    • 2020-01-14
    相关资源
    最近更新 更多