简体   繁体   English

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

[英]Display y axis value horizontal line drawn In bar chart

I am using (matplotlib.pyplot as plt) matplotlib to draw a bar chart. 我使用(matplotlib.pyplot作为plt)matplotlib来绘制条形图。 On that bar chart I have drawn a horizontal line using axhline() function in grey colour . 在该条形图上,我使用灰色的axhline()函数绘制了一条水平线。 I want that the point (value on y axis = 42000) from where that horizontal line starts should also display the value ie 42000 . 我希望水平线开始的点(y轴上的值= 42000)也应显示值,即42000。 What to do? 该怎么办?

This is my current image: 这是我目前的形象:

在此输入图像描述

On the image below, see the '39541.52' point? 在下图中,请参阅'39541.52'点? I want to display exactly like that on my image and my point value is '42000' 我希望在我的图像上显示完全相同的值,我的点值是'42000'

在此输入图像描述

A label can be created eg using ax.text() . 可以使用ax.text()创建标签。 To position the label a nice trick is to use a transform that allows to use axes coordinates for the x position and data coordinates for the y position. 要定位标签,一个很好的技巧是使用允许使用x位置的轴坐标和y位置的数据坐标的变换。

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

Complete code: 完整代码:

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()

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM