python matplotlib: istogramma
31 Marzo 2011
Con questa classe e matplotlib, creo un grafico “named bars”,
da una lista[(nome, valore),] o da un dizionario{nome: valore},
passatogli come argomento.
Utilizzando molto sqlite ho considerato le liste nel formato
tipico del metodo fetchall().
codice:
import numpy as np import matplotlib.pyplot as plt class Bars(object): def __init__(self, data = {}): if type (data) == dict: print "dict" self.data = data elif type(data) == list: self.data = {} print "list" for item in data: self.data[item[0]] = item[1] else: print "'%s' in ingresso errato: necessari Liste o Dizionari" %type(data) try: n_bars = len(self.data) pts = self.data.values() teams = self.data.keys() ind = np.arange(n_bars) # the x locations for bar width = 0.2 # the width of the bars plt.subplot(111) bars = plt.bar(ind + 0.2, pts, width, color='b', align = 'center') plt.title('Classifica') plt.ylabel('pts') plt.xticks(ind + width , teams, size = 'x-small', rotation = 15) for bar in bars: val = int(bar.get_height()) x_pos = bar.get_x() + 0.4 y_pos = bar.get_height() - 0.1 * bar.get_height() plt.text(x_pos, y_pos, '%d'%val, ha='center', va='bottom', size = 'small', rotation = 90) plt.show() except AttributeError: print "Grafico non rappresentabile, controllare dato in ingresso" if __name__ == '__main__': # data = 'str' # data = {'Boy SAN': 100, 'Cioppersson': 105, 'Stella Blu Kativeria': 120, 'Pippo': 180, # 'MiddleSboron': 98, 'Nizzi': 140, 'F.C.Zipangolo': 165, 'Real Ancona': 135, # 'Gnagna': 88, 'Cento': 98} data = [('Boy SAN', 100), ('Cioppersson', 105), ('Stella Blu Kativeria', 120), ('Pippo', 180), ('MiddleSboron', 98), ('Nizzi', 140), ('F.C.Zipangolo', 165), ('Real Ancona', 135), ('Gnagna', 88), ('Cento', 98)] hg = Bars(data)
Categorie:python
Commenti recenti