pyplot

Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias:

1
import matplotlib.pyplot as plt

Function

plot()

The plot() function is used to draw points in a diagram. This function takes two parameters for specifying points in the diagram.

Parameter1 is a array that define the range on x-axis.

Paramete21 is a array that define the range on y-axis.

By default, the plot() function draws a line from point to point.

point to point

Example

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
import numpy as np

x=np.array([1,3])
y=np.array([2,4])

plt.plot(x,y)
plt.show()

So we draw a line from position(1,2) to (3,4)

To plot only the markers, you can use shortcut string notation parameter ‘o’

1
plt.plot(x,y,'o')

Multiple points

You can add more elements in the np.array(), so that we can define more points.

1
2
3
4
x=np.array([1,5,7,10])
y=np.array([1,10,1,10])

plt.plot(x,y)

As we can see, we draw a line from position(1,1) to (5,10) then to (7,1) and to (10,10)

Scatter

With Pyplot, you can use the scatter() function to draw a scatter plot.

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

plt.scatter(x, y)
plt.show()

Bars

With Pyplot, you can use the bar() function to draw bar graphs:

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
import numpy as np

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x,y)
plt.show()

Histogram

A histogram is a graph showing frequency distributions.

It is a graph showing the number of observations within each given interval.

In Matplotlib, we use the hist() function to create histograms.

1
2
3
4
5
6
7
import matplotlib.pyplot as plt
import numpy as np

x = np.random.normal(170, 10, 250)

plt.hist(x)
plt.show()

Pie Charts

You can use pie() function to draw pie charts.

1
2
3
4
5
6
7
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])

plt.pie(y)
plt.show()

Add labels to the pie chart with the label parameter.

1
2
3
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)