减少图例sns中的小数

2024-04-26 06:42:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想在图例中显示hrmin

ax = sns.lineplot(x="time", y="qL",
                  hue="hr", style="hr", ci=0, palette="tab10",
                  markers=True, dashes=False, legend="full", data=file)

这是我尝试过的,但显然不起作用。我还附上了结果图

plt.setp(ax.get_legend().get_texts()[:4])

Tags: cigettimestylehraxminhue
1条回答
网友
1楼 · 发布于 2024-04-26 06:42:02

答复

你可以:

  • 使用ax.get_legend_handles_labels()提取当前图例标签
  • 然后用new_labels = [label[:-3] for label in labels]操纵它们
  • 最后,通过ax.legend()设置新标签

例如,请参见下面的代码

代码

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot([0, 1], [1, 2], label = '08:00:00')
ax.plot([0, 1], [2, 0], label = '10:30:00')
ax.legend(title = 'hr')

handles, labels = ax.get_legend_handles_labels()
new_labels = [label[:-3] for label in labels]
ax.legend(handles, new_labels, title = 'hr')

plt.show()

输出

enter image description here

首先,我添加了一个带有ax.legend(title = 'hr')的图例标题,如果您使用seaborn,这将自动完成。但是,ax.get_legend_handles_labels()不提取图例标题,只提取标签。这样,在设置新标签时,需要使用ax.legend(handles, new_labels, title = 'hr')再次指定图例标题。也许有一种更优雅的方式可以做到这一点

相关问题 更多 >

    热门问题