Pyplot is a sub-module of the matplotlib library for Python.
It is a library consisting of a collection of functions/methods used for plotting simple 2D graphs using Python.
Pyplot can be imported using import matplotlib.pyplot
.
To clarify, matplotlib is a pre-existing library, while pyplot is a part/module of the matplotlib library installed alongside matplotlib.
For simplicity, from here onwards, pyplot in the code will be referred to as plt
. This can be done in the code using import matplotlib.pyplot as plt
.
pyplot
Before we start making graphs, we have the ability to add/change different characteristics of the graphs we want to create. For example:
Changing the name of the axis using plt.xlabel('X-Axis name')
or plt.ylabel('Y-Axis name')
Changing the title of the graph with plt.title('new title')
Creating a legend with the syntax plt.legend([""])
Changing the color scheme
The data for scatter graphs, bar graphs, etc., can be created with the help of lists or even dictionaries. For example:
# X-axis and Y-axis valuesx = [10,20,30,40,50]y = [23,34,45,56,67]
A line graph is a graph that shows change over time or the relation between two or more categories of data.
These can be created using plt.plot(x value set , y value set)
.
Note: The process of making a scatter chart is mostly the same as that of making a line graph, with the main difference being that the graph syntax used is
plt.scatter(X-Axis values, Y-axis values)
.
# Example of a Line graphimport matplotlib.pyplot as pltx = [10,20,30,40,50]y = [63,36,92,36,46]plt.plot(x,y)plt.show()
Bar graphs are used to compare things between different groups or to track changes over time.
These can be created using plt.bar(X-Axis values, Y-axis values)
.
Note: The process of making a histogram is mostly the same as that of making a bar graph, with the main difference being the graph syntax used is
plt.hist(X-Axis values, Y-axis values)
.
# Example of a Bar Graphfrom matplotlib import pyplot as pltbrand ='Brand A','Brand B','Brand C','Brand D'sales = [30,60,29,50]plt.bar(brand,sales)plt.legend(["Sales"])plt.show()
A pie chart is a type of graph that represents data in a circular graph. Each division shows the relative size of the data. Pie charts can be used to show the percentages of a whole.
These can be made by inserting plt.pie(data values)
. The pie chart slices will be divided based on the ratio of the data values.
# Example of a Pie Chartimport matplotlib.pyplot as pltx = [10,20,30,40]plt.pie(x)plt.show()
Note: The distance of each slice can be specified while creating the pie chart by adding the
explode = (Distance of each slice from center)
after the data set with a comma.
For example:
import matplotlib.pyplot as pltx = [10,20,30,40]e =(1,0,2,4)plt.pie(x,explode = e)plt.show()