AssertionError:不兼容的大小:参数“height”必须是长度2或标量(Matplotlib, Python 2.7,绘制图表)

时间:2022-01-27 20:24:05

A new day brought new problem with Python, unfortunately :/

新的一天给Python带来了新的问题,不幸的是:/

I have a file generated by my other app written in Java. This app generates files with some data, it's kind a random stuff 'cause I'm not able to say how many rows each file would have. Example file looks like this:

我有一个由我的另一个用Java编写的应用程序生成的文件。这个应用会生成一些数据,这是随机的,因为我不知道每个文件有多少行。示例文件如下所示:

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

And I want to draw a chart with use of this data. On X axis I would like to have formatted dates, and on Y axis numbers from the first column of my file. Heres my lovely python code:

我想用这些数据画一个图表。在X轴上我想要格式化日期,在Y轴上我文件第一列的数字。下面是我可爱的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")

Everything is fine, if file.txt had a one, single row. When it has more rows, python code gives me an error:

一切都很好,如果文件。txt有一个单行。当它有更多行时,python代码会给我一个错误:

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

And I don't really know how to fix it. Its fine, if file.txt had one row but as I wrote earlier: I'm not able to say how many rows would file.txt have (it depends on my Java app).

我也不知道怎么修理。它的好,如果文件。txt有一行,但正如我前面所写的:我不能说出要文件多少行。txt有(这取决于我的Java应用)。

Anybody? I use Python 2.7 and Matplotlib on Kubuntu 12.04.

有人知道吗?我在kubuntu12.04上使用Python 2.7和Matplotlib。

2 个解决方案

#1


12  

It's because dates only has 2 values. The length of dates and the length of values must be the same for matplotlib to know what to do. If values was a scalar then all the bars would have the same height

因为日期只有两个值。对于matplotlib来说,日期的长度和值的长度必须是相同的,这样才能知道要做什么。如果值是标量,那么所有的条都有相同的高度

#2


1  

Thanks I think I figured it out - the problem was with the readFile(arg) function, it should look like this:

谢谢,我想我算出来了——问题是readFile(arg)函数,应该是这样的:

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)

#1


12  

It's because dates only has 2 values. The length of dates and the length of values must be the same for matplotlib to know what to do. If values was a scalar then all the bars would have the same height

因为日期只有两个值。对于matplotlib来说,日期的长度和值的长度必须是相同的,这样才能知道要做什么。如果值是标量,那么所有的条都有相同的高度

#2


1  

Thanks I think I figured it out - the problem was with the readFile(arg) function, it should look like this:

谢谢,我想我算出来了——问题是readFile(arg)函数,应该是这样的:

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)