使用两组数据绘制Pandas数据框的图表

3
我正在使用Pandas和Matplotlib尝试复制Tableau中的这个图形:

Tableau Graph

目前,我有以下代码:
group = df.groupby(["Region","Rep"]).sum()
total_price = group["Total Price"].groupby(level=0, group_keys=False)
total_price.nlargest(5).plot(kind="bar")

这将生成以下图形:

enter image description here

它正确地分组了数据,但是否可能让其类似于Tableau中显示的分组方式?

1个回答

3

您可以使用相应的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()

enter image description here


太棒了!谢谢!现在要实际去理解它在做什么。 :) - Jon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接