gpt4 book ai didi

python - 如何在 matplotlib.hlines 中设置标签

转载 作者:太空狗 更新时间:2023-10-30 02:08:27 26 4
gpt4 key购买 nike

我正在尝试为 matplotlib.hlines 中的每一行添加标签:

from matplotlib import pyplot as plt
plt.hlines(y=1, xmin=1, xmax=4, label='somelabel1')
plt.hlines(y=2, xmin=2, xmax=5, label='somelabel2')

我需要一个带有两条水平线的图,每条线的“y”轴上都有标签。而不是它,我得到了一个没有标签的图,只有坐标(参见示例图像)。是否可以将每行的标签放入图中?

enter image description here

最佳答案

label kwarg 用于指定显示在 legend 中的字符串,不一定在行本身。如果您希望标 checkout 现在您的绘图中,您需要使用 text对象代替

plt.hlines(y=1, xmin=1, xmax=4)
plt.text(4, 1, ' somelabel1', ha='left', va='center')

plt.hlines(y=2, xmin=2, xmax=5)
plt.text(2, 2, 'somelabel2 ', ha='right', va='center')

enter image description here

如果您想要为这些设置特殊的 y 轴标签,则可以使用自定义格式化程序。

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.hlines(y=1, xmin=1, xmax=4)
plt.hlines(y=2, xmin=2, xmax=5)

def formatter(y, pos):
if y == 1:
return 'label1'
elif y == 2:
return 'label2'
else:
return y

plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(formatter))

enter image description here

关于python - 如何在 matplotlib.hlines 中设置标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com