首页 > 解决方案 > 将图例的颜色与条形图 python 中的条相匹配?

问题描述

我正在尝试将我的图例的颜色与图表中的条形相匹配。我特别强调了这些酒吧作为兴趣点,因为它们在我的 ylim 之外。问题是,我的图例将颜色显示为黑色,而不是我想要的颜色。

下面是我用来绘制图表的函数,以及图表的图像。

def seaborn_plot(dataset,times):

    sns.set_style('darkgrid')
    sns.set_color_codes("muted")
    data_ = dataset
    time_list = []
    data_list = []

    for i, v in enumerate(data_):
          if data_[i] > 80000:
              data_list.append(('ED={:.2f}'.format(data_[i])))
              time_list.append(("Hour {}:".format(times[i])))


    df = pd.DataFrame(data = {'times_new':time_list,
                              'data_list':data_list})

    red = 'r'
    blue = 'b'
    colors = []
    for i in range(len(data_)):
        if data_[i] > 80000:
            color = red
            colors.append(color)
        else:
            color2 = blue
            colors.append(color2)

    graph = sns.barplot(x=times, y=data_ , palette = colors, label = time_list)
    graph.set_xlabel("Time (Hours)", fontsize = 10, fontweight = 'bold');
    graph.set_ylabel("Euclidean Distance", fontsize = 10, fontweight = 'bold');
    graph.set_ylim([0, 80000])

    leg = mp.gca().legend(labels = df["times_new"] + df["data_list"])  

    return graph

结果图像:

我的图表的图像

标签: pythonseaborn

解决方案


您可以遍历生成的条形图并将满足条件的条形图用作图例的句柄。由于 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()

结果图

请注意,通过将条形图用作图例句柄,当每个条形图具有单独的颜色时,此方法也适用。


推荐阅读