gpt4 book ai didi

python - 使用 Panda 和 Matplotlib 绘制 2 个堆叠系列

转载 作者:行者123 更新时间:2023-12-01 02:13:59 25 4
gpt4 key购买 nike

我正在拼命尝试用 Matplot 创建漂亮的图形,但这并不是一件容易的事。为了结合上下文,我有两个系列(serie1serie2)。对于每个

我有 3 个组(Group1、Group2 和 Group3)。对于每个小组,我都有一些主题和值(value)观。每个系列通过不同的变量(主题)描述了几个个体(G1,G2,G3)的行为。代码是:

import pandas as pd
d = {"ThemeA": [25,34,75], "ThemeB": [0,71,18], "ThemeC": [2,0,0], "ThemeD":[1,14,0] }
serie1 = pd.DataFrame(data = d, index=["Groupe 1", "Groupe 2", "Groupe 3"] )
serie1= serie1.loc[:,:].div(serie1.sum(1), axis=0) * 100

d = {"ThemeA": [145,10,3], "ThemeB": [10,1,70], "ThemeC": [34,1,2], "ThemeD":[3,17,27]}
serie2= pd.DataFrame(data = d, index=["Groupe 1", "Groupe 2", "Groupe 3"])
serie2= serie2.loc[:,:].div(serie2.sum(1), axis=0) * 100

现在我想制作一个图表来显示用户数据:

ax = fig.add_subplot(111) 
ax = serie1.plot(kind='barh', ax=ax, width=0.2, stacked=True, position=0, sharex=True,
sharey=True, legend=True, figsize = (6,2))

serie2.plot(kind='barh', ax=ax, width=0.2, stacked=True, position=1.6,
sharex=True, sharey=True, legend=False)
ax.grid(False)
plt.ylim([-0.5, 2.5])

我能够得到以下图表:

Badddd

但我想将图例移到底部。如果我尝试这样做,

ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), 
fancybox=True, shadow=True, ncol=5)

我得到以下输出,其中标签太多。

Arrrrrrrrggg

当然,我希望在图例中只看到每个标签一次。
如果有人有奇迹般的解决方案,我会接受!提前致谢。

最佳答案

您可以使用比需要更长的 x 轴,以便为图例留出空白空间

# calculate the size of the longer column (max of row sums)
max_col = serie2.sum(axis=1).max()
# increase the size of the x axis a factor of 1.4
xlim(0, max_col*1.4)

如果您希望图例位于底部,那么当您调用 legend 时,您实际上是在从两个图中绘制标签。您需要删除重复的标签。为此,您可以使用字典。

from collections import OrderedDict

fig = figure()
figsize(6,2)
ax = fig.add_subplot(111)

serie1.plot(kind='barh', ax=ax, width=0.2, stacked=True, position=0,
sharex=True, sharey=True)

serie2.plot(kind='barh', ax=ax, width=0.2, stacked=True, position=1.6,
sharex=True, sharey=True)

handles, labels = gca().get_legend_handles_labels()
my_labels = OrderedDict(zip(labels, handles))
legend(my_labels.values(), my_labels.keys(), loc='upper center',
bbox_to_anchor=(0.5, -0.1), fancybox=True, shadow=True, ncol=5)

ax.grid(False)
ylim([-0.5, 2.5])

然后你会得到:

enter image description here

关于python - 使用 Panda 和 Matplotlib 绘制 2 个堆叠系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48527614/

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