2015-05-14 7 views
18

Ho generato un diagramma a barre, come posso visualizzare il valore della barra su ogni barra?Come visualizzare il valore della barra su ogni barra con pyplot.barh()?

trama attuale:

enter image description here

Quello che sto cercando di ottenere:

enter image description here

Il mio codice:

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

x = [u'INFO', u'CUISINE', u'TYPE_OF_PLACE', u'DRINK', u'PLACE', u'MEAL_TIME', u'DISH', u'NEIGHBOURHOOD'] 
y = [160, 167, 137, 18, 120, 36, 155, 130] 

fig, ax = plt.subplots()  
width = 0.75 # the width of the bars 
ind = np.arange(len(y)) # the x locations for the groups 
ax.barh(ind, y, width, color="blue") 
ax.set_yticks(ind+width/2) 
ax.set_yticklabels(x, minor=False) 
plt.title('title') 
plt.xlabel('x') 
plt.ylabel('y')  
#plt.show() 
plt.savefig(os.path.join('test.png'), dpi=300, format='png', bbox_inches='tight') # use format='svg' or 'pdf' for vectorial pictures 

risposta

38

Add:

for i, v in enumerate(y): 
    ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold') 

risultato:

enter image description here

I valori y v sono sia la x-posizione ei valori di stringa per ax.text, e convenientemente il barplot ha una metrica di 1 per ogni barra, così l'enumerazione i è la posizione y.

+2

forse sostituire use va = 'center', invece di "i + .25" per allineamento orizzontale – mathause

1

ho notato api example code contiene un esempio di diagramma a colonna con il valore della barra visualizzate su ciascuna barra:

""" 
======== 
Barchart 
======== 

A bar plot with errorbars and height labels on individual bars 
""" 
import numpy as np 
import matplotlib.pyplot as plt 

N = 5 
men_means = (20, 35, 30, 35, 27) 
men_std = (2, 3, 4, 1, 2) 

ind = np.arange(N) # the x locations for the groups 
width = 0.35  # the width of the bars 

fig, ax = plt.subplots() 
rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std) 

women_means = (25, 32, 34, 20, 25) 
women_std = (3, 5, 2, 3, 3) 
rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std) 

# add some text for labels, title and axes ticks 
ax.set_ylabel('Scores') 
ax.set_title('Scores by group and gender') 
ax.set_xticks(ind + width/2) 
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) 

ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) 


def autolabel(rects): 
    """ 
    Attach a text label above each bar displaying its height 
    """ 
    for rect in rects: 
     height = rect.get_height() 
     ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, 
       '%d' % int(height), 
       ha='center', va='bottom') 

autolabel(rects1) 
autolabel(rects2) 

plt.show() 

uscita:

enter image description here

FYI What is the unit of height variable in "barh" of matplotlib? (fin d'ora, ci non è un modo semplice per impostare un'altezza fissa per ogni barra)

+1

Sembra che get_x() arrotonda il numero anche se l'originale x ha posizioni decimali. Come si ottengono più posizioni decimali da visualizzare? – ru111

Problemi correlati