Line Graph In Python

Armando Di Cicco

For my AT exemplary, I decided to learn how to create a line graph in python - something that we didn't cover in class.

In order to do this, I utilized the matolib website. They explained the functions of their library, and offered some examples of code. I used both the in-depth explanations of the functions, as well as the example code to teach myself how to create a line graph.

Although creating the graph and entering the data points were fairly straightforward, I still encountered several difficulties. The first difficulty I encountered was finding a way to differentiate between two lines, seeing as they would be the same color. I eventually fixed this by researching and finding that there was a built in color function inside the "plot" function. 

The second difficulty I encountered was creating a legend for the graph. The function that was designed to create a legend for my graph was not working with the code I had created. After much troubleshooting, I stumbled upon the answer. In an attempt to make my code more efficient, I tried to plot both lines in a single line of code. Whilst this was more efficient, it led the program to believe that both data sets were part of the same line, not allowing me to label both data sets. I fixed this by returning each data set to its own individual line of code.

 

FINAL CODE

 

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 10:36:27 2016

@author: ASUS
"""

##Importing the libraries
import matplotlib.pyplot as pyplot #imports the directory "pyplot" 

##Setting up the titles
pyplot.title("Graph", fontsize = 22)#Sets a title for the graph
pyplot.xlabel("X Axis", fontsize = 18)#Sets a title for the X axis
pyplot.ylabel("Y Axis", fontsize = 18)#Sets a title for the Y axis
#Changes the font and color of the titles

##Plotting the axis and data
pyplot.axis([0, 20, 0, 20])#Sets the limits for both of the axis
#First two numbers are the min and max of the X axis, last two are the same but for Y
pyplot.plot([1,5,10,15,20], [0,3,12,12,2],label = 'line1', )
pyplot.plot([1,5,10,15,20], [1,5,10,15,20],"r",label = 'line2')
#As of right now, there is no way to put both data sets in the same line without 
#messing up the legend

##Creating the legend
pyplot.legend(loc='upper left')#creates and places the legend

pyplot.show() #shows the graph until it is dismissed