matplotlib 如何为堆叠条形图中的特定条形分配颜色列表

juzqafwq  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(187)

我有一个堆叠条形图,显示了按性别分组的不同合并症的计数。
女性用'pink'表示,男性用'lightskyblue'表示。
为了更清楚地表明'None'不仅仅是另一种合并症,我希望'None'(患者没有合并症)使用不同的颜色来突出它:'lightcoral'代表女性,'royalblue'代表男性。
这是我目前使用colors = ['lightskyblue', 'pink']的堆叠条形图:

comorbidity_counts_by_gender = df.groupby('sex_female')[comorbidity_columns].sum()

comorbidity_counts_by_gender = comorbidity_counts_by_gender[comorbidity_counts_by_gender.sum().sort_values(ascending=True).index].T

colors = ['lightskyblue', 'pink']
bars = comorbidity_counts_by_gender.plot(kind='barh', stacked=True, figsize=(8, 8), color=colors, width=0.8)

plt.title('Distribution of Comorbidities by Gender')
plt.xlabel('Count')
plt.ylabel('')
bars.legend(title='Gender', loc="upper left", bbox_to_anchor=(1, 1), frameon=False)

plt.show()

字符串


的数据
无论我怎么尝试,我似乎都无法为“无”栏提供不同的颜色对。这里有两种方法,我试图解决这个问题,但对我不起作用:

尝试1:

colors = [['royalblue', 'lightcoral'] if comorbidity == 'None' else ['lightskyblue', 'pink'] for comorbidity in comorbidity_counts_per_gender.index]


这将导致ValueError:Invalid color(“lightskyblue”,“pink”)

尝试2:

colors = []
for comorbidity in comorbidity_counts_by_gender.index:
  if comorbidity == 'None':
    colors = ['royalblue', 'lightcoral']
  else:
    colors = ['lightskyblue', 'pink']


对于任何列,它始终使用['lightskyblue','pink']。

mqkwyuun

mqkwyuun1#

下面是一个直接更改相应条形图颜色的示例:

import pandas as pd
from matplotlib import pyplot as plt

def setcolors(ax, name="None", colors=["royalblue", "lightcoral"]):
    """
    Function to set the colours for the bars for a given category name.
    """

    # get labels
    ytl = ax.get_yticklabels()
    numlabels = len(ytl)
    
    # find the index of the given named label
    for i, t in enumerate(ytl):
        if t.get_text() == name:
            break
    
    # get the matplotlib rectangle objects representing the bars
    # (note this relies on nothing else having been added to the plot)
    rects = ax.get_children()[0:2 * numlabels]
    nrects = [rects[i], rects[numlabels + i]]
    
    # loop over the two bars for the given named label and change the colours
    for rect, color in zip(nrects, colors):
        rect.set_color(color)
        rect.set_edgecolor("none")

# some mock data
df = pd.DataFrame(
    {
        "Male": [5, 1, 3, 1],
        "Female": [4, 2, 2, 0]
    },
    index=["Smoking", "Hypertension", "None", "Hyperthyroidism"],
)

bars = df.plot(kind="barh", stacked=True, color=["lightskyblue", "pink"])

# change the colors
setcolors(bars)

plt.show()

字符串


的数据
请注意,默认情况下(* 我认为 *),表示条形的Rectangle对象应该是get_children()返回的列表中的第一个对象。但是,如果您向图中添加更多内容,则情况 * 可能 * 并非如此。

相关问题