显示在条形图ch中绘制的y轴值水平线

2024-09-29 21:39:28 发布

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

我正在使用(matplotlib.pyplot as plt)matplotlib绘制条形图。在那个条形图上,我用灰色的axhline()函数画了一条水平线。我希望从水平线开始的点(y轴上的值=42000)也应该显示值,即42000。怎么办?

这是我现在的照片:

enter image description here

在下图中,看到“39541.52”点了吗?我想在我的图像上显示完全一样的值,我的点值是‘42000’

enter image description here


Tags: 函数图像matplotlibas绘制plt照片条形图
1条回答
网友
1楼 · 发布于 2024-09-29 21:39:28

可以创建标签,例如使用ax.text()。要定位标签,一个很好的技巧是使用一个允许使用x位置的轴坐标和y位置的数据坐标的变换。

ax.text(1.02, 4.2e4, "42000", .. , transform=ax.get_yaxis_transform())

完整代码:

import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
x = [0,1,2,3]
y = np.array([34,40,38,50])*1e3
norm = matplotlib.colors.Normalize(30e3, 60e3)
ax.bar(x,y, color=plt.cm.plasma_r(norm(y)) )
ax.axhline(4.2e4, color="gray")
ax.text(1.02, 4.2e4, "42000", va='center', ha="left", bbox=dict(facecolor="w",alpha=0.5),
        transform=ax.get_yaxis_transform())
plt.show()

enter image description here

相关问题 更多 >

    热门问题