Display y axis value horizontal line drawn In bar chart

给你一囗甜甜゛ 提交于 2019-12-18 16:52:40

问题


I am using (matplotlib.pyplot as plt) matplotlib to draw a bar chart. On that bar chart I have drawn a horizontal line using axhline() function in grey colour . I want that the point (value on y axis = 42000) from where that horizontal line starts should also display the value i.e 42000 . What to do?

This is my current image:

On the image below, see the '39541.52' point? I want to display exactly like that on my image and my point value is '42000'


回答1:


A label can be created e.g. using 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.

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



来源:https://stackoverflow.com/questions/43560801/display-y-axis-value-horizontal-line-drawn-in-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!