The matplotlib Library
In this section, you will have a chance to exercise your understanding of lists and indexing and apply your knowledge to plotting data. You will also learn how to import libraries into Python. A library in Python generally contains several methods that can be used to perform a specific set of functions. The matplotlib library contains a host of methods useful for plotting data. Try running this snippet of code in Repl.it:
import matplotlib.pyplot as plt x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] plt.plot(x,y) plt.xlabel('X') plt.ylabel('Y') plt.title('Test Plot') plt.show() plt.savefig('plot1.png')
The import
command instructs Python to import the matplotlib library. The extra qualifier as plt
is added so that the name of the plotting object can be shortened to plt
. This set of commands plots the data contained in the x
list against the data contained in the y
list. The methods xlabel
, ylabel
, and title
are useful for adding annotation to the plot. For completeness, the show
method is given so that users understand that this command is useful for rendering the plot in many different Python IDEs. However, Repl.it is a web-based IDE, and the savefig
command will be more appropriate and useful for the rendering of data plots. The leftmost Repl.it window is where you can find the plot file 'plot1.png'. Click on that file to view the plot generated by this code. To return to your Python code, click on 'main.py' in the leftmost window. We will discuss the uploading and downloading of files as we delve into the course more deeply. For now, realize that, for each new plot you would like to generate, you can use the savefig method with a different filename in single quotes (such as plot2.png, plot3.png, and so on).
Make sure to mirror and practice the examples provided in the video tutorial in Repl.it.
Source: https://www.youtube.com/embed/XFUmdgK4Gwk This work is licensed under a Creative Commons Attribution 3.0 License.