0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.