<p>我认为这个<a href="https://stackoverflow.com/questions/22787209/how-to-have-clusters-of-stacked-bars-with-python-pandas/22845857#22845857">function solution by @jrjc</a>对我的理解来说是相当复杂的,因此,我宁愿稍微改变我自己的东西并调整它</p>
<p>因此,我花了一些时间才明白,当为绘图创建第二个图例时,python会自动删除第一个图例,而此时必须使用<code>add_artist()</code></p>
<p>添加第二个图例的另一个先决条件是命名绘图,并将.add_artist()方法应用于该特定绘图,以便python知道将新绘图粘贴到何处</p>
<p>简言之,这就是我如何创造我心目中的情节,我希望这些评论能让它变得更清晰,对任何人都有用</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap as coloring
import matplotlib.patches as mpatches
# copy the dfs below and use pd.read_clipboard() to reproduce
df_1
A B C D E
Mg 10 15 23 25 27
Ca 30 33 0 20 17
df_2
A B C D E
Mg 20 12 8 40 10
Ca 7 26 12 22 16
hatches=(' ', '//')
colors_ABCDE=['tomato', 'gold', 'greenyellow', 'forestgreen', 'palevioletred']
dfs=[df_1,df_2]
for each_df, df in enumerate(dfs):
#I name the plot as "figure"
figure=df.plot(ax=plt.subplot(111), kind="barh", \
stacked=True, hatch=hatches[each_df], \
colormap=coloring.from_list("my_colormap", colors_ABCDE), \
figsize=(7,2.5), position=len(dfs)-each_df-1, \
align='center', width=0.2, edgecolor="darkgrey", \
legend=False) #I had to False the legend too
legend_1=plt.legend(df_1.columns, loc='center left', bbox_to_anchor=(1.0, 0.5), fontsize=12)
patch_hatched = mpatches.Patch(facecolor='beige', hatch='///', edgecolor="darkgrey", label='hatched')
patch_unhatched = mpatches.Patch(facecolor='beige', hatch=' ', edgecolor="darkgrey", label='non-hatched')
legend_2=plt.legend(handles=[patch_hatched, patch_unhatched], loc='center left', bbox_to_anchor=(1.15, 0.5), fontsize=12)
# as soon as a second legend is made, the first disappears and needs to be added back again
figure.add_artist(legend_1) #python now knows that "figure" must take the "legend_1" along with "legend_2"
</code></pre>
<p><a href="https://i.stack.imgur.com/Xh6Ym.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xh6Ym.png" alt="plot with two legends"/></a></p>
<p>我敢肯定,它可以更加优雅和自动化</p>