python - 将图例的颜色与条形图 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
结果图像:
解决方案
您可以遍历生成的条形图并将满足条件的条形图用作图例的句柄。由于 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()
请注意,通过将条形图用作图例句柄,当每个条形图具有单独的颜色时,此方法也适用。
推荐阅读
- video - A帧切换模板导致声音(视频?)重叠
- c# - 使用空白键值对建模 json
- python - torchvision.datasets 中数据集的 .data 属性不适用于 ImageFolder?
- linux - 如何从文件 Bash 中调用主机列表的变量
- javascript - 选择当前可见的 DIV ID 并存储在变量中
- blazor - 为什么我在提交 Blazor Server 表单时收到 404 错误?
- python - 将多列分组为几列-Pandas 数据框
- react-native - react-native-material-textfield(Android)中的多行文本输入样式问题
- python - python Kivy:按钮触发事件
- asp.net-core - 在断开连接的服务器上构建 .Net Core Web App 时出现 NuGet 问题