簡體   English   中英

在y軸上添加標簽以顯示matplotlib中水平線的y值

[英]Add a label to y-axis to show the value of y for a horizontal line in matplotlib

如何在下圖中顯示的水平紅線上添加字符串標簽? 我想在該行旁邊的y軸標簽上添加類似“ k = 305”的內容。 藍點只是其他一些數據,其值無關緊要。 為了解決這個問題,您可以繪制任何類型的數據。 我的問題是關於紅線。

plt.plot((0,502),(305,305),'r-')
plt.title("ALS+REG")

情節

可以使用Axes.axhline(y)繪制一條水平線。
添加標簽將通過使用Axes.text() 棘手的一點是要確定放置該文本的坐標。 由於y坐標應該是繪制線條的數據坐標,但是標簽的x坐標應該獨立於數據(例如,允許不同的軸比例),因此我們可以使用混合變換,其中x變換是軸ylabel的變換,而y變換是數據坐標系。

import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import numpy as np; np.random.seed(42)

N = 120
x = np.random.rand(N)
y = np.abs(np.random.normal(size=N))*1000
mean= np.mean(y)

fig, ax=plt.subplots()
ax.plot(x,y, ls="", marker="o", markersize=2)
ax.axhline(y=mean, color="red")

trans = transforms.blended_transform_factory(
    ax.get_yticklabels()[0].get_transform(), ax.transData)
ax.text(0,mean, "{:.0f}".format(mean), color="red", transform=trans, 
        ha="right", va="center")

plt.show()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM