在Pandas 和Matplotlib 中聚類堆疊條形
簡介
簡介簡介
<code class="python">import pandas as pd import matplotlib.cm as cm import matplotlib.pyplot as plt def plot_clustered_stacked(dfall, labels=None, title="multiple stacked bar plot"): 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="bar", linewidth=0, stacked=True, ax=axe, legend=False, grid=False) 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_x(rect.get_x() + 1 / float(n_df + 1) * i / float(n_col)) rect.set_hatch("/" * int(i / n_col)) #edited part rect.set_width(1 / float(n_df + 1)) axe.set_xticks((np.arange(0, 2 * n_ind, 2) + 1 / float(n_df + 1)) / 2.) axe.set_xticklabels(df.index, rotation = 0) 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="/" * i)) l1 = axe.legend(h[:n_col], l[:n_col]) if labels is not None: l2 = plt.legend(n, labels) axe.add_artist(l1) return axe</code>
簡介
簡介
<code class="python"># create fake dataframes df1 = pd.DataFrame(np.random.rand(4, 5), index=["A", "B", "C", "D"], columns=["I", "J", "K", "L", "M"]) df2 = pd.DataFrame(np.random.rand(4, 5), index=["A", "B", "C", "D"], columns=["I", "J", "K", "L", "M"]) df3 = pd.DataFrame(np.random.rand(4, 5), index=["A", "B", "C", "D"], columns=["I", "J", "K", "L", "M"]) # plot clustered stacked bar plot_clustered_stacked([df1, df2, df3], ["df1", "df2", "df3"])</code>
此解決方案利用 Pandas 和 Matplotlib 函式庫的功能。程式碼如下:
要使用此函數,只需傳入資料幀和可選參數(例如標籤和標題)清單即可。它將產生帶有陰影線的簇狀堆疊條,以區分資料幀。<code class="python">plot_clustered_stacked([df1, df2, df3], ["df1", "df2", "df3"], cmap=plt.cm.viridis)</code>
示例
以下是使用此函數的示例:
其他功能您可以透過傳遞cmap 參數來自訂條形的顏色:結論此解決方案提供了一種靈活便捷的方法來建立聚類堆積長條圖。您可以輕鬆修改程式碼以滿足資料視覺化的特定要求。以上是如何在 Pandas 和 Matplotlib 中建立聚類堆積長條圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!