<P>由于在{{CD1>}中添加传奇是一个复杂的、广泛的步骤,请考虑使用@ jjjc与<a href="https://stackoverflow.com/a/22845857/1422451">function solution</a>引用的非常链接。不过,您需要根据水平条形图的需要调整该函数。具体而言:</p>
<ul>
<li>为颜色映射和<code>DataFrame.plot</code>调用添加一个参数</li>
<li>对于水平版本,将条形图从<code>kind='bar'</code>调整为<code>kind='barh'</code></li>
<li>将x交换为y行:<code>rect.set_y(rect.get_y() + 1 / float(n_df + 1) * i / float(n_col))</code></li>
<li>在<code>rect.set_height(1 / float(n_df + 1))</code>行中用<code>width</code>交换<code>height</code></li>
<li>调整<code>axe.set_xticks</code>和<code>axe.set_xticklabels</code>的<code>np.arange(0, 120, 20)</code>值</li>
</ul>
<p><strong>功能</strong></p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.cm as cm
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap as coloring
def plot_clustered_stacked(dfall, labels=None, title="multiple stacked bar plot", H="//",
colors_ABCDE=['tomato', 'gold', 'greenyellow', 'forestgreen', 'palevioletred'], **kwargs):
"""
CREDIT: @jrjc (https://stackoverflow.com/a/22845857/1422451)
Given a list of dataframes, with identical columns and index, create a clustered stacked bar plot.
labels is a list of the names of the dataframe, used for the legend
title is a string for the title of the plot
H is the hatch used for identification of the different dataframe
"""
n_df = len(dfall)
n_col = len(dfall[0].columns)
n_ind = len(dfall[0].index)
axe = plt.subplot(111)
for df in dfall : # for each data frame
axe = df.plot(kind="barh",
linewidth=0,
stacked=True,
ax=axe,
legend=False,
grid=False,
colormap=coloring.from_list("my_colormap", colors_ABCDE),
edgecolor="darkgrey",
**kwargs) # make bar plots
h,l = axe.get_legend_handles_labels() # get the handles we want to modify
for i in range(0, n_df * n_col, n_col): # len(h) = n_col * n_df
for j, pa in enumerate(h[i:i+n_col]):
for rect in pa.patches: # for each index
rect.set_y(rect.get_y() + 1 / float(n_df + 2) * i / float(n_col))
rect.set_hatch(H * int(i / n_col)) #edited part
rect.set_height(1 / float(n_df + 2))
axe.set_xticks(np.arange(0, 125, 20))
axe.set_xticklabels(np.arange(0, 125, 20).tolist(), rotation = 0)
axe.margins(x=0, tight=None)
axe.set_title(title)
# Add invisible data to add another legend
n=[]
for i in range(n_df):
n.append(axe.bar(0, 0, color="gray", hatch=H * i, edgecolor="darkgrey"))
l1 = axe.legend(h[:n_col], l[:n_col], loc=[1.01, 0.5])
if labels is not None:
l2 = plt.legend(n, labels, loc=[1.01, 0.1])
axe.add_artist(l1)
return axe
</code></pre>
<p><strong>呼叫</strong></p>
<pre><code>plt.figure(figsize=(10, 4))
plot_clustered_stacked([df_1, df_2],["df_1", "df_2"])
plt.show()
plt.clf()
plt.close()
</code></pre>
<p><strong>输出</strong></p>
<p><a href="https://i.stack.imgur.com/bZYbj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bZYbj.png" alt="Plot Output"/></a></p>