Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display y axis value horizontal line drawn In bar chart

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:

enter image description here

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'

enter image description here

like image 861
Devashish Nigam Avatar asked Apr 22 '17 15:04

Devashish Nigam


1 Answers

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

enter image description here

like image 65
ImportanceOfBeingErnest Avatar answered Oct 21 '22 12:10

ImportanceOfBeingErnest