Вы можете l oop через сгенерированные столбцы и использовать столбцы, удовлетворяющие условию, в качестве маркеров легенды. Поскольку seaborn не возвращает список столбцов (в отличие от plt.bars()
), столбцы могут быть получены из возвращенного ax
(предположим, что другие столбцы еще не нарисованы на том же графике):
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_style('darkgrid')
sns.set_color_codes("muted")
data_ = np.random.randint(20000, 100000, 24)
times = np.arange(0, 24)
y_limit = 80000
colors = ['r' if d > y_limit else 'b' for d in data_]
ax = sns.barplot(x=times, y=data_, palette=colors)
ax.set_xlabel("Time (Hours)", fontsize=10, fontweight='bold')
ax.set_ylabel("Euclidean Distance", fontsize=10, fontweight='bold')
ax.set_ylim([0, y_limit])
handles = [bar for bar in graph.containers[0] if bar.get_height() > y_limit]
labels = [f'Hour {" " if h < 10 else ""}{h}: ED={ed:,.0f}' for ed, h in zip(data_, times) if ed > y_limit]
ax.legend(handles, labels, bbox_to_anchor=[1.02, 1], loc='upper left')
plt.tight_layout()
plt.show()
Обратите внимание, что при использовании полосок в качестве маркеров легенды этот подход также будет работать, когда каждая полоса будет иметь индивидуальный цвет.