2012-08-22 10 views
9

Un nuevo día traído nuevo problema con Python, por desgracia:/AssertionError: tamaños incompatibles: argumento de 'altura' debe ser de longitud 2 o escalar (Matplotlib, Python 2.7, tablas de dibujo)

Tengo un archivo generado por mi otra aplicación escrita en Java. Esta aplicación genera archivos con algunos datos, es algo aleatorio porque no puedo decir cuántas filas tendría cada archivo. El archivo de ejemplo tiene este aspecto:

3 Sat Jan 21 00:00:00 2012 
7 Sun Mar 11 00:00:00 2012 
5 Fri Jan 1 00:00:00 2010 
4 Sat Feb 5 00:00:00 2011 
8 Sun Apr 11 00:00:00 2010 
4 Wed Aug 24 00:00:00 2011 
8 Sat Feb 20 00:00:00 2010 
3 Thu Oct 13 00:00:00 2011 
9 Fri Dec 17 00:00:00 2010 
4 Tue Jul 20 00:00:00 2010 
8 Fri Dec 2 00:00:00 2011 
6 Mon May 31 00:00:00 2010 
5 Mon May 16 00:00:00 2011 
8 Mon Apr 30 00:00:00 2012 
3 Thu Oct 28 00:00:00 2010 
1 Tue Jun 19 00:00:00 2012 
7 Wed Sep 8 00:00:00 2010 

Y quiero dibujar un gráfico con el uso de estos datos. En el eje X, me gustaría tener las fechas formateadas y los números del eje Y de la primera columna de mi archivo. Aquí está mi preciosa código Python:

# -*- coding: utf-8 -*- 
#!/usr/bin/env python 
import wx 
import matplotlib 
matplotlib.use("TkAgg") 
import matplotlib.pyplot as pl 
import datetime 

def monthNum(month) : 
     if month == "Jan" : 
      return 1 
     elif month == "Feb" : 
      return 2 
     elif month == "Mar" : 
      return 3 
     elif month == "Apr" : 
      return 4 
     elif month == "May" : 
      return 5 
     elif month == "Jun" : 
      return 6 
     elif month == "Jul" : 
      return 7 
     elif month == "Aug" : 
      return 8 
     elif month == "Sep" : 
      return 9 
     elif month == "Oct" : 
      return 10 
     elif month == "Nov" : 
      return 11 
     elif month == "Dec" : 
      return 12 

def convertDate(dateTime) : 
     line = dateTime.split(' ') 
     date = (str(line[2]) + "-" + str(monthNum(line[1])) + "-" + str(line[4])) 
     return date 

def readFile(filename) : 
     values = [] 
     dates = [] 
     try : 
       with open(filename, "r") as openedFile: 
         for line in openedFile : 
           line = line.strip() 
           data = line.split("\t") 
           values.append(int(data[0])) 
           newDate = convertDate(data[1]) 
           dates.append(datetime.datetime.strptime(newDate, "%d-%m-%Y").date()) 
     except IOError : 
       print("IOERROR") 
     except ValueError : 
       print("VALUE ERROR") 
     if len(values) != 0 and len(dates) != 0 : 
       drawChart(values, dates, filename) 

def drawChart(values, dates, filename): 
     fig = pl.figure(dpi=60,figsize=(18, 10)) 
     ax = fig.add_subplot(1,1,1) 
     fig.subplots_adjust(left=0.1, right=0.95, top=0.95, bottom=0.2) 
     ax.bar(range(len(dates)), values, facecolor='#777777', align='center', width=0.5, ecolor='black') 
     pl.axis('tight') 
     ax.set_xticks(range(len(dates))) 
     pl.yticks(values) 
     ax.set_xticklabels(dates, rotation = 90) 
     pl.savefig(filename + ".png") 
     pl.show() 
     pl.close() 

readFile("file.txt") 

todo está bien, si tenían un file.txt uno, una hilera. Cuando tiene más filas, el código python me da un error:

VALUE ERROR 
Traceback (most recent call last): 
    File "test.py", line 71, in <module> 
    readFile("file.txt") 
    File "test.py", line 56, in readFile 
    drawChart(values, dates, filename) 
    File "test.py", line 62, in drawChart 
    ax.bar(range(len(dates)), values, facecolor='#777777', align='center', width=0.5, ecolor='black') 
    File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 4733, in bar 
    nbars) 
AssertionError: incompatible sizes: argument 'height' must be length 2 or scalar 

Y realmente no sé cómo solucionarlo. Está bien, si file.txt tenía una fila, pero como escribí anteriormente: no puedo decir cuántas filas tendría file.txt (depende de mi aplicación Java).

¿Alguien? Uso Python 2.7 y Matplotlib en Kubuntu 12.04.

+0

lo ¿contiene la variable 'valores'? – Sheena

+0

@Sheena: contiene una lista de números de la primera columna de mi archivo – Katie

Respuesta

12

Es porque las fechas solo tienen 2 valores. La longitud de las fechas y la longitud de los valores deben ser las mismas para que matplotlib sepa qué hacer. Si los valores fue un escalar a continuación, todas las barras tendrían la misma altura

1

Gracias Creo que lo he descubierto - el problema era con la función readFile (arg), que debería tener este aspecto:

def readFile(filename) : 
    values = [] 
    dates = [] 
    openedFile = open(filename, "r") 
    content = openedFile.readlines() 
    openedFile.close() 
    for line in content : 
     line = line.strip() 
     data = line.split("\t") 
     values.append(int(data[0])) 
     newDate = self.convertDate(data[1]) 
     dates.append(newDate) 
    print(values) 
    print(dates) 
Cuestiones relacionadas