Generation de graphe en python (histogramme/Camenbert).

From Tuxunix
Jump to: navigation, search

Exemple Graphe


HistogramTest.png


TestPie.png

Python graphe

Code


   1.#!/usr/bin/python2.4
   2.# -*- coding: utf-8 -*-
   3.       
   4.#
   5.#@Name classMatplotlib.py
   6.#@Note generate histogram graphics
   7.#@Author pierre@tuxedo.fr
   8.#@Date 26/03/2009
   9.#@Depends
  10.#@Licence NO COPYRIGHT! GNU/GPL (RIGHT TO INFORMATION FOR ALL)
  11.#@Version 0.1
  12.#
  13.       
  14.       
  15.import os, sys, random
  16.import numpy as np
  17.import matplotlib.pyplot as plt
  18.from pylab import *
  19.sys.path.append ("Class/LOG")
  20.from log import log
  21.       
  22.       
  23.class matplotlib(object):
  24.    """ functions histogram or pie (camenbert); WARNING histogram accept
  25.    values int only! and pie accept float values or int!; args : dictionnar"""
  26.    def __init__(self, dico):
  27.        self.dico=dico
  28.        self.logMatplot=log("./sibylla.log")
  29.       
  30.    def countBar(self, dico):
  31.        return len(self.dico.keys())
  32.       
  33.    def histogram(self, nbrBar, titleGraph):
  34.        """WARNING histogram accept values int only! args : nbrBar,
  35.        titleGraph"""
  36.        N = int(nbrBar)
  37.        listVal=[]
  38.        listKeys=[]
  39.        listleg=[]
  40.        ind = np.arange(N) # the x coordonate of the left side bars
  41.        width = 0.40 # the width of the bars
  42.        std=(1)
  43.        listeColor= ["g", "r", "b", "m"]
  44.        fig = plt.figure()
  45.        ax = fig.add_subplot(111)
  46.        for keys, values in self.dico.items():
  47.            listVal.append(int(values))
  48.            listKeys.append(keys)
  49.            listleg.append(keys +": "+str(values)+"%")
  50.        for keys, values in self.dico.items():
  51.            couleur=int(random() * 4)
  52.            #print couleur
  53.            ax.bar(ind, listVal, width, color=listeColor[couleur],\
  54.            yerr=std, capsize=1, align='edge', orientation='vertical')
  55.            #height = int(values)
  56.        ax.legend(listleg)
  57.        # add some
  58.        ax.set_ylabel('Percent usage %')
  59.        ax.set_title(titleGraph)
  60.        ax.set_xticks(ind+width)
  61.        ax.set_xticklabels(listKeys)
  62.        #Save histogram
  63.        fig.savefig(titleGraph+'.png')
  64.        self.logMatplot.writeLog("MATPLOTLIB histogram generate with file name : %s.png [done]."%titleGraph).
  64.        #Clear figure
  64.        clf()
  65.
  66.
  67.        #show graphs
  68.        #plt.show()
  69.       
  70.    def pieGraph(self, nbrPart, titlePie):
  71.        """Pie accept float values or int! ;-) ; args : nbrPart,
  72.        titlePie"""
  73.        listFracs=[]
  73.        del(listFracs[:])
  74.        listLabels=[]
  73.        del(listLabels[:])
  75.        percentValues=0
  76.        def somme(i,j) : return float(i)+float(j)
  77.       
  78.        # make a square figure and axes
  79.        figure(1, figsize=(6,6))
  80.        for keys, values in self.dico.items():
  81.            listFracs.append(values)
  82.            listLabels.append(keys)
  83.        #gestion nbr de valeur inferieur a 100%
  84.        percentValues = reduce(somme, listFracs)
  85.        if float(percentValues) < float(100):
  86.           listLabels.append("Others")
  87.           listFracs.append(100-percentValues)
  88.        elif float(percentValues) > float(100):
  89.            self.logMatplot.writeLog("MATPLOTLIB pie generate : \
  90.              Values > 100% [Error].")
  91.            os.sys.exit(1)
  92.            print "SORTIR"
  93.       
  94.        pie(listFracs, labels=listLabels, autopct='%1.1f%%',\
  95.            shadow=False)
  96.        title(titlePie, bbox={'facecolor':'0.8', 'pad':5})
  97.            savefig(titlePie+'.png')
  98.        self.logMatplot.writeLog("MATPLOTLIB pie generate with file\
  99.            name : %s.png \
 100.            [done]."%titlePie)
 100.        #Clear figure
 100.        clf()
 101.        #show pie
 102.        #show()
 103.       
 104.# Main
 105.#Exemple graph
 106.if __name__ == '__main__' :
 107.    dico = {}
 108.    dico['computer'] = '10.6'
 109.    dico['mouse'] ='30'
 110.    dico['keyboard'] ='40.2'
 111.    dico['toto1'] ='5'
 112.     
 113.    Graphic=matplotlib(dico)
 114.    #Graphic.histogram(Graphic.countBar(dico), "Test")
 115.    Graphic.pieGraph(Graphic.countBar(dico), "TestPie")

By TuXedo


Récupère la taille d'un FS, graphe l'utilisation, envoie par mail

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import matplotlib, os, sys, re, subprocess, smtplib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
 
def getData(nameServer, directory):
  l=[]
  p=os.popen('ssh -q '+nameServer+' "df -B1 '+ directory +'"')
  for line in p.readlines():
    l.append(re.split(r'\s{1,}',line.strip()))
  p.close()
  used=l[2][1]
  avail=l[2][2]
  label1=l[2][3]
  label2=l[2][4]
  label=label1+' '+label2
  graphCreat(nameServer, used, avail,label,label1)
 
 
def graphCreat(nameGraph,used,avail,label,label1):
  x = [used, avail]
  plt.pie(x, labels = ['humanbytes(used)', 'humanbytes(avail)'])
  plt.figure(figsize = (10, 10))
  plt.pie(x, labels = ["Used : " + humanbytes(used) + " ("+label1+")","Free : "+ humanbytes(avail)])
  plt.legend()
  plt.suptitle(nameGraph+" - disk used : "+label, bbox={'facecolor':'0.8', 'pad':5})
  plt.savefig(nameGraph+'.png')
 
 
def sendMail(lstImg):
#  Create message container.
  msgRoot = MIMEMultipart('related')
  msgRoot['Subject'] = "Occupation disque"
  msgRoot['From'] = "xxxxxx@xxxxx.fr"
  msgRoot['To'] = "xxxxxx@xxxxxx.fr"
  msgRoot['Cc'] = "xxxxxx@xxxxx.fr"
  msgRoot.preamble = 'This is a multi-part message in MIME format.'
 
  msgAlternative = MIMEMultipart('alternative')
  msgRoot.attach(msgAlternative)
  msgText = MIMEText('Bonjour, \n\n Surveillance FS des machines correspondant.\n\n Cordialement,\n')
  msgAlternative.attach(msgText)
 
  for i in lstImg:
    cpt=1
    img = open(i+".png", 'rb').read()
    msgImg = MIMEImage(img, 'png')
    msgImg.add_header('Content-ID', '<image'+str(cpt)+'>')
    msgImg.add_header('Content-Disposition', 'inline', filename=i+".png")
    cpt=cpt+1
    msgRoot.attach(msgImg)
 
  s = smtplib.SMTP('localhost')
  s.sendmail(msgRoot['From'], msgRoot['To'], msgRoot.as_string())
  s.quit()
 
def humanbytes(B):
   B = float(B)
   KB = float(1024)
   MB = float(KB ** 2)
   GB = float(KB ** 3)
   TB = float(KB ** 4)
 
   if B < KB:
      return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte')
   elif KB <= B < MB:
      return '{0:.2f} KB'.format(B/KB)
   elif MB <= B < GB:
      return '{0:.2f} MB'.format(B/MB)
   elif GB <= B < TB:
      return '{0:.2f} GB'.format(B/GB)
   elif TB <= B:
      return '{0:.2f} TB'.format(B/TB)
 
 
#
#MAIN
#
 
if __name__ == '__main__' :
  getData("server1", "/base/ora")
  getData("server2", "/object/dev")
  getData("server3", "/git/repos")
  lstImg=['server1', 'server2', 'server2']
  sendMail(lstImg)

Autres