python中同一类别的固定颜色条形图

2024-05-28 22:58:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的dataframe,如下所示:

    Condition   State     Value
0       A        AM      0.775651
1       B        XP      0.700265
2       A       HML      0.688315
3       A     RMSML      0.666956
4       B      XAD       0.636014
5       C       VAP      0.542897
6       C     RMSML      0.486664
7       B      XMA       0.482742
8       D      VCD       0.469553

现在我想要一个带有每个值的条形图,如果条件相同,每个状态的颜色也相同。我尝试了以下python代码:

^{pr2}$

但我不能正确地得到每种情况下的传说。我得到了下面的情节。
Figure

那么我应该如何为每种情况得到正确的图例呢?非常感谢任何帮助,谢谢。在


Tags: dataframevalue情况condition条件amvcdxp
2条回答

可以直接从数据创建图例的句柄和标签:

labels = df['Condition'].unique()
handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]
plt.legend(handles, labels, title="Conditions")

完整示例:

^{pr2}$

enter image description here

因此,我没有太多直接从pandas进行绘图,但是您必须访问句柄并使用它来构造句柄和标签的列表,这些句柄和标签可以传递给plt.legend。在

s.plot(kind='barh', color=[colors[i] for i in df['Condition']])
# Get the original handles.
original_handles = plt.gca().get_legend_handles_labels()[0][0]

# Hold the handles and labels that will be passed to legend in lists.
handles = []
labels = []
conditions = df['Condition'].values
# Seen conditions helps us make sure that each label is added only once.
seen_conditions = set()
# Iterate over the condition and handle together.
for condition, handle in zip(conditions, original_handles):
    # If the condition was already added to the labels, then ignore it.
    if condition in seen_conditions:
        continue
    # Add the handle and label.
    handles.append(handle)
    labels.append(condition)
    seen_conditions.add(condition)

# Call legend with the stored handles and labels.
plt.legend(handles, labels)

相关问题 更多 >

    热门问题