0

I am writing a function to display a graph with multiple lines. Each line represents a column in my numpy array. My x-axis is the variable year and my y-axis is my np.array. I am struggling to find the right place to insert the nested list coorectly in the code to show the line of each field on the graph depending of the year

year = [2000,2001,2002,2003]
notes = [[10,11,11,14],[11,14,15,16],[15,14,12,11],[14,11,10,14]]
legend = {'maths':1, 'philosophy': 2, 'english': 3, 'biology': 4}

def PlotData (data,legend):
    for i in data:
        plt.plot(i,color = 'red' , marker = '.', 
                 markersize = 10, linestyle = 'solid')
        plt.legend(legend,loc ='upper left')
        plt.title('Final Examination')
        plt.xlabel('Year')
        plt.ylabel('Marks')
        plt.show()

PlotData((year,notes), legend)

1 Answer 1

2

You first need to separate the x-axis from y-axis, because you have only have 1 array for x and multiple for y.

year, notes = data

Then you need to actually specify the x-axis in your code by adding year before i.

plt.plot(year, i , marker = '.', 
                 markersize = 10, linestyle = 'solid')

lastly you need to move the rest of the code outside of the loop since it only needs to be executed once.

  • i removed the color=red to make the graph more clear with multiple colors.
year = [2000,2001,2002,2003]
notes = [[10,11,11,14],[11,14,15,16],[15,14,12,11],[14,11,10,14]]
legend = {'maths':1, 'philosophy': 2, 'english': 3, 'biology': 4}

def PlotData (data,legend):
    year, notes = data
    for i in notes:
        plt.plot(year, i , marker = '.', 
                 markersize = 10, linestyle = 'solid')
    plt.legend(legend,loc ='upper left')
    plt.title('Final Examination')
    plt.xlabel('Year')
    plt.ylabel('Marks')
    plt.show()

PlotData((year,notes), legend)

result:

enter image description here

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

2 Comments

aim97 , if each mark in a nested list is in the form for example( [10,11,11,14] for [maths, phylosophy,english,biology] in 2000 ...) , i need to use another for loop to pick up each year, right?
@Cressydeborbon if so you are better of reformatting your list (probably take the transpose using numpy) or iterate over columns instead of rows, to put data in format suitable for display, than working directly with this format (which may cause problems with matplotlib with the order of the points).

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.