Гистограмма с фиксированным цветом для той же категории в питоне - PullRequest
3 голосов
/ 08 марта 2019

У меня есть простой 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:

Data_Control = pd.ExcelFile('Bar_plot_example.xlsx') 
df_Control= Data_Control.parse('Sheet2')# my dataframe
s = 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()

Но я не могу правильно получить легенду для каждого условия.Я получаю следующий сюжет.
Figure

Итак, как мне получить правильную легенду для каждого условия?Любая помощь высоко ценится, спасибо.

Ответы [ 2 ]

2 голосов
/ 08 марта 2019

Так что я не очень много работал с графиками непосредственно из панд, но вам придется обращаться к ручкам и использовать их для создания списков ручек и меток, которые вы можете передать 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)
1 голос
/ 08 марта 2019

Вы можете создавать маркеры и метки для легенды непосредственно из данных:

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()

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...