Vla*_*lad 4 python matplotlib python-3.x
我试图在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')
Run Code Online (Sandbox Code Playgroud)
我需要一个带有两条水平线的图,每条线在“ y”轴上带有标签。取而代之的是,我得到的图没有标签,只有坐标(请参见示例图像)。是否可以将每条线的标签放入图中?
该label kwarg是指定在随即出现的字符串legend,不一定就行本身。如果您希望标签显示在绘图中,则需要使用一个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')
Run Code Online (Sandbox Code Playgroud)
如果您需要这些特殊的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))
Run Code Online (Sandbox Code Playgroud)