Cody Wirth
Cody Wirth

Reputation: 3

Receiving an error when trying to plot with matplotlib

I am trying to graph my growth1 function so that is uses matplotlib to plot days on x axis and the total population on the y axis for a 30 day period.

However, when running my code through the terminal I keep receiving this error:

ValueError: x and y must have same first dimension

All I am trying to do is plot the following data:

 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

etc. but for 30 days.

Here is my code:

#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)

What am I doing wrong?

Upvotes: 0

Views: 59

Answers (1)

supermitch
supermitch

Reputation: 2992

The problem is simply that you are not storing your population data anywhere:

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)

What matplotlib error is telling you is that the dimensions of your arguments to plot(x, y) must match. In your case, x was range(days + 1) but populationList was just [3]. Needless to say, the length of the x-values didn't match the length of the y-values.

Upvotes: 2

Related Questions