[英]Add a label to y-axis to show the value of y for a horizontal line in matplotlib
可以使用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.