尝试使用matplotlib绘图时收到错误

时间:2015-09-19 04:37:55

标签: python matplotlib

我正在尝试绘制我的growth1函数,以便使用matplotlib在x轴上绘制天数,在y轴上绘制总人口30天。

然而,当我通过终端运行我的代码时,我一直收到这个错误:

ValueError: x and y must have same first dimension

我要做的就是绘制以下数据:

 1  |      3.00
 2  |      6.00
 3  |      9.00
 4  |     12.00
 5  |     15.00
 6  |     18.00
 7  |     21.00
 8  |     24.00
 9  |     27.00
10  |     30.00

等。但是30天。

这是我的代码:

#1/usr/bin/env python3

import matplotlib.pyplot as pyplot

def growth1(days, initialPopulation):
    population = initialPopulation
    populationList = []
    populationList.append(initialPopulation)
    for day in range(days):
        population = 3 + population

    pyplot.plot(range(days +1), populationList)
    pyplot.xlabel('Days')
    pyplot.ylabel('Population')
    pyplot.show()


growth1(100, 3)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

问题只是您没有将population数据存储在任何地方:

import matplotlib.pyplot as pyplot

def growth1(days, initialPopulation):
    population = initialPopulation
    populationList = [initialPopulation]  # A bit cleaner
    for day in range(days):
        population += 3  # A bit cleaner
        populationList.append(population)  # Let's actually add it to our y-data!

    pyplot.plot(range(days + 1), populationList)
    pyplot.xlabel('Days')
    pyplot.ylabel('Population')
    pyplot.show()

growth1(100, 3)

matplotlib错误告诉您的是plot(x, y)的参数的维度必须匹配。在您的情况下,xrange(days + 1),但populationList仅为[3]。不用说,x值的长度与y值的长度不匹配。