为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

大话西游666 2021-11-30 10:27:32
我有一个简单的dataframe如下:    Condition   State     Value0       A        AM      0.7756511       B        XP      0.7002652       A       HML      0.6883153       A     RMSML      0.6669564       B      XAD       0.6360145       C       VAP      0.5428976       C     RMSML      0.4866647       B      XMA       0.4827428       D      VCD       0.469553现在我想要一个带有每个值的条形图,如果条件相同,则每个状态都有相同的颜色。我尝试了以下python代码:Data_Control = pd.ExcelFile('Bar_plot_example.xlsx') df_Control= Data_Control.parse('Sheet2')# my dataframes = pd.Series(df_Control.iloc[:,2].values, index=df_Control.iloc[:,1])colors = {'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'}s.plot(kind='barh', color=[colors[i] for i in df_Control['Condition']])plt.legend()但是我无法为每种情况正确获得图例。我得到以下情节。那么我应该如何为每个条件获得正确的图例?非常感谢任何帮助,谢谢。
查看完整描述

2 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

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


labels = df['Condition'].unique()

handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]

plt.legend(handles, labels, title="Conditions")

完整示例:


u = """    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"""


import io

import pandas as pd

import matplotlib.pyplot as plt



df = pd.read_csv(io.StringIO(u),sep="\s+" )

s = pd.Series(df.iloc[:,2].values, index=df.iloc[:,1])

colors = {'A': 'r', 'B': 'b', 'C': 'g', 'D':'k'}

s.plot(kind='barh', color=[colors[i] for i in df['Condition']])


labels = df['Condition'].unique()

handles = [plt.Rectangle((0,0),1,1, color=colors[l]) for l in labels]

plt.legend(handles, labels, title="Conditions")


plt.show()

//img1.sycdn.imooc.com//61a58c3c0001650904520334.jpg

查看完整回答
反对 回复 2021-11-30
?
达令说

TA贡献1821条经验 获得超6个赞

因此,我没有过多地直接从 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)


查看完整回答
反对 回复 2021-11-30
  • 2 回答
  • 0 关注
  • 254 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信