亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用熊貓圖獲得兩個圖例,一個用于堆疊條的顏色,一個用于條的陰影?

如何使用熊貓圖獲得兩個圖例,一個用于堆疊條的顏色,一個用于條的陰影?

MM們 2022-10-18 14:38:06
我一直試圖理解這篇文章的答案,以便填充兩個不同的傳說。我為每個條創建了一個帶有不同陰影的聚集堆積條圖,下面的代碼與上述帖子的答案有點不同。但是我無法弄清楚如何獲得一個帶有顏色的圖例和一個帶有陰影的圖例。顏色圖例應對應于 A、B、C、D、E,并且陰影圖例應指示“有”如果條帶陰影線,“無”如果沒有陰影線。import matplotlib.pyplot as pltfrom matplotlib.colors import LinearSegmentedColormap as coloring# copy the dfs below and use pd.read_clipboard() to reproducedf_1     A   B   C   D   EMg  10  15  23  25  27Ca  30  33   0  20  17df_2     A   B   C   D   EMg  20  12   8  40  10Ca   7  26  12  22  16hatches=(' ', '//')colors_ABCDE=['tomato', 'gold', 'greenyellow', 'forestgreen', 'palevioletred']dfs=[df_1,df_2]for each_df, df in enumerate(dfs):    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")plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5), fontsize=12)我設法得到的情節是:任何想法如何創建兩個圖例并將它們放在另一個旁邊或一個在另一個下面?提前謝謝^_^
查看完整描述

2 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

由于添加圖例matplotlib是一個復雜而廣泛的步驟,因此請考慮使用您引用的 @jrjc函數解決方案的鏈接。但是,您需要根據水平條形圖的需要調整功能。具體來說:

  • 為顏色圖和DataFrame.plot調用添加參數

  • 將條形圖從kind='bar'到調整kind='barh'為水平版本

  • 將 x 換成 y 行:rect.set_y(rect.get_y() + 1 / float(n_df + 1) * i / float(n_col))

  • 換線widthheightrect.set_height(1 / float(n_df + 1))

  • 調整axe.set_xticksaxe.set_xticklabelsnp.arange(0, 120, 20)_

功能

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

稱呼


plt.figure(figsize=(10, 4))

plot_clustered_stacked([df_1, df_2],["df_1", "df_2"])

plt.show()


plt.clf()

plt.close()

輸出

http://img1.sycdn.imooc.com//634e49ff0001ca1e07250302.jpg

查看完整回答
反對 回復 2022-10-18
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

我認為@jrjc 的這個功能解決方案對我的理解來說相當令人困惑,因此,我更愿意稍微改變我自己的東西并進行調整。


所以,我花了一些時間才明白,當為情節創建第二個圖例時,python 會自動刪除第一個圖例,這是add_artist()必須使用的時候。


添加第二個圖例的另一個先決條件是命名圖并將 .add_artist() 方法應用于該特定圖,以便 python 知道將新部分粘貼在哪里。


簡而言之,這就是我設法創建我想到的情節的方式,我希望這些評論能讓它更清晰,對任何人都有用。


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"

有兩個傳說的情節

http://img1.sycdn.imooc.com//634e4a1700018b2206050164.jpg我很確定它可以更加優雅和自動化。


查看完整回答
反對 回復 2022-10-18
  • 2 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號