gpt4 book ai didi

python - 用两组绘制 Pandas 数据框

转载 作者:太空宇宙 更新时间:2023-11-03 15:54:20 25 4
gpt4 key购买 nike

我正在使用 Pandas 和 matplotlib 尝试从画面中复制这张图:

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 显示的那样对其进行分组?

最佳答案

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

关于python - 用两组绘制 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44548913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com