gpt4 book ai didi

python - 我可以分享不同轴上多个 Pandas 地 block 的传说吗?

转载 作者:太空宇宙 更新时间:2023-11-04 09:24:35 25 4
gpt4 key购买 nike

我想使用 Pandas 和 matplotlib 在不同的轴上绘制多个堆叠的条形图

以下最小示例的问题在于它为每个轴创建了一个图例。

import pandas as pd
import matplotlib.pyplot as plt

d1 = {'a': 1, 'b': 10}
d2 = {'a': 5, 'b': 5}
df = pd.DataFrame([d1,d2])
d1 = {'a': 9, 'b': 3}
d2 = {'a': 5, 'b': 4}
df2 = pd.DataFrame([d1,d2])

fig, axes = plt.subplots(2,1,sharex=True)
df.plot.barh(stacked=True,ax=axes[0])
axes[0].set_ylabel('DataFrame 1')
df2.plot.barh(stacked=True,ax=axes[1])
axes[1].set_ylabel('DataFrame 2')

enter image description here

有没有办法共享所有轴的图例?可以将图例移到绘图区域之外吗?图例可能相当大。

最佳答案

是的,如果所有图例都相同,您可以捕获其中一个并将其放在 plt 上:

# grab the legend handles and lables
h, l = axes[0].get_legend_handles_labels()

# remove all the subplot legends
for ax in axes: ax.get_legend().remove()

# add one legend on `plt`
plt.legend(h,l, loc=(1.05, 0.8))

输出:

enter image description here

关于python - 我可以分享不同轴上多个 Pandas 地 block 的传说吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58457083/

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