What is matplotlib?
Matplotlib is a library in python programming language. We need to import this library using 'import' , before using it's features.
Use of matplotlib:
Matplotlib is a library in python. It helps in embedding plots. Whenever we want to plot a agraph in python we use this library.
Some types of graphs we can draw using matplotlib:
1.Line plot
2.Bar plot
3.Histogram
4.Scatter-plot
5.Pie-chart
6.Contour plot:
7.Box plot
8.Working with images
First we need to install matplotlib using 'pip' command.
Use the following command in the terminal:
pip install matplotlib
Importing matplotlib:
import matplotlib.pyplot as plt
This imports the matplotlib library to be used for plotting.
Axes:
This is what you think of as 'a plot', it is the region of the image with the data space.
A given figure can contain many Axes, but a given Axes object can only be in one Figure.
The Axes contains two (or three in the case of 3D) Axis objects (be aware of the difference between Axes and Axis)
which take care of the data limits (the data limits can also be controlled via the axes.Axes.set_xlim() and axes.Axes.set_ylim() methods).
Each Axes has a title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).
The Axes class and its member functions are the primary entry point to working with the OO interface.
Axis:
These are the number-line-like objects.
They take care of setting the graph limits and generating the ticks (the marks on the axis) and ticklabels (strings labeling the ticks).
The location of the ticks is determined by a Locator object and the ticklabel strings are formatted by a Formatter.
The combination of the correct Locator and Formatter gives very fine control over the tick locations and labels.
Artist:
Basically everything you can see on the figure is an artist (even the Figure, Axes, and Axis objects).
This includes Text objects, Line2D objects, collections objects, Patch objects ... (you get the idea).
When the figure is rendered, all of the artists are drawn to the canvas. Most Artists are tied to an Axes;
such an Artist cannot be shared by multiple Axes, or moved from one to another.
- An empty figure with no Axes
fig = plt.figure()
Output:<Figure size 432x288 with 0 Axes>
- A figure with a single Axes
fig, ax = plt.subplots()
Output:
1.Line graph:
Steps we follow to draw this graph:
1.First, we define the x-axis and the y-axis values as lists.
2.Using .plot() we plot the graph
3.If we want , we can name the x-axis and the y-axis.
4.We can also give a title to our graph.
5.We use .show() to view our graph
Example:
1.
2.
Two or more lines on same graph:
Example:
3.
4.
Here, we plot two lines on same graph. We differentiate between them by giving them a name(label) which is passed as an argument of .plot() function.
The small rectangular box giving information about type of line and its color is called legend. We can add a legend to our plot using .legend() function.
5.
x = [1,2,3]
y = [2,4,6]
plt.plot(x, y, label = "line1")
x1 = [1,2,3]
y1 = [4,8,3]
plt.plot(x1, y1, label = "line2")
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Two lines on one graph')
plt.legend()
plt.show()
Output:
- Bar Chart
We pass x-coordinates along with the required heights. We can give names to x-axis coordinates.
Syntax:
matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
- The bars are at position x.
- Height refers to the height of the bars.
- We can pass the same height for all the bars , or , pass a list of different heights for each bars.
- 'align' is the alignment of the bars with the x-axis.
- 'center': Center the base on the x positions.
- 'edge': Align the left edges of the bars with the x positions.
- We can add colours to the face of the bars as well as to the edges of the bars.
- We can give linewidth of the bar.
- If we put the linewidth to be 0 , then their won't be any bar edge.
- We can provide tick_labels.
- The default value of bottom is 0.
6.
x = [15,82,33,6,95]
y = [27,48,69,32,0]
plt.bar(x,y)
plt.show()
Output:
7.
x = [5,2,3,6,9]
y = [27,48,69,32,100]
plt.bar(x,y)
plt.show()
Output:
8.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
h = [10, 24, 36, 40, 5]
tick_label = ['one', 'two', 'three', 'four', 'five']
plt.bar(x, h, tick_label = tick_label, width = 0.6, color = ['blue', 'black'])
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Bar graph!')
plt.show()
Output:
This is how we add colour to our bar graph.
- Histogram
To draw a histogram we use, matplotlib.pyplot.hist.
Syntax:
matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, data=None, kwargs)
x: it takes an array or a sequence if array.
bins : bins defines the number of equal width bins in the the given range.
range:The lower and upper range of the bins.
density: It is a boolean value , and its default is False. If it is True,it draws and returns a probability density.
weights: array-like or None, default: None
Steps to draw a histogram:
Step 1: Install Matplotlib package
pip install matplotlib
Step 2: Collect data for the histogram
For example: We need age of hundred people.br>
Step 3: Determine the number of bins
Step 4: Plot the histogram in Python using matplotlib
Examples
9.
y = [27,48,69,32,0]
plt.hist(y)
y = [5,2,3,6,9]
plt.hist(y)
plt.show()
Output:
11.
ges = [2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
range = (0, 100)
bins = 10
plt.hist(ages, bins, range, color = 'green',histtype = 'bar', rwidth = 0.8)
plt.xlabel('Age group')
plt.ylabel('No. of people affected by corona')
plt.show()
- Scatter Plot :
To draw a histogram we use, matplotlib.pyplot.scatter.
Syntax:
matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=, edgecolors=None, *, plotnonfinite=False, data=None, kwargs)
A scatter plot of x vs y.
- x, y:float or array-like
- s:float or array-like
- c:array-like or list of colours or colour
- The plot function will be faster for scatterplots where markers don't vary in size or color.
Examples:
12.
x = [5,2,3,6,9]
y = [27,48,69,32,100]
plt.scatter(x,y)
plt.show()
13.
x = [15,82,33,6,95]
y = [27,48,69,32,0]
plt.scatter(x,y)
plt.show()
14.
x = [15,82,33,6,95,2,3,6,8,22,5,44,11,74,14,95,86,23]
y = [27,48,69,32,0,15,82,33,6,95,2,0,36,69,43,31,15,2]
plt.scatter(x,y)
plt.show()
15.
x = [15,82,33,6,95,2,3,6,8,22,5,44,11,74,14,95,86,23]
y = [27,48,69,32,0,15,82,33,6,95,2,0,36,69,43,31,15,2]
plt.scatter(x, y, label= "stars", color= "red", marker= "", s=30)
plt.show()
This is how we change the label and colour of the marker.
- Pie-chart:
A Pie Chart is a circular statistical plot that can display only one series of data.
Examples:
16.
company = ['DevIncept', 'Adobe', 'Infosys', 'Amazon']
s = [8, 3, 4, 6]
colors = ['r', 'y', 'g', 'b']
plt.pie(s, labels = company, colors=colors, startangle=90, shadow = True, explode = (0.2, 0, 0, 0), radius = 1.2, autopct = '%1.1f%%')
plt.legend()
plt.show()
17.
- Contour graph:
- Contour plots are aslo called Level Plots.
- Contour plots are a way to show a three-dimensional area on a two-dimensional plane.
- It shows the X and the Y variable on the Y axis , and the Z on the X axis.
- contour() function draws contour lines.
- contourf() function draws filled contours.
- Both functions require three parameters x,y and z.
17.
xlist = np.linspace(-10.0, 10.0, 100)
ylist = np.linspace(-5.0,53.0, 100)
X, Y = np.meshgrid(xlist, ylist)
Z = np.sqrt(X**2 + Y**2)
fig,ax=plt.subplots(1,1)
cp = ax.contourf(X, Y, Z)
fig.colorbar(cp)
ax.set_title('Filled Contours Plot')
ax.set_ylabel('y (cm)')
plt.show()
Output:
- Box Plot:
- A Box Plot is also known as Whisker plot
- In a box plot, we draw a box from the first quartile to the third quartile.
Syntax:
matplotlib.pyplot.boxplot(x, notch=None, sym=None, vert=None, whis=None, positions=None, widths=None, patch_artist=None, bootstrap=None, usermedians=None, conf_intervals=None, meanline=None, showmeans=None, showcaps=None, showbox=None, showfliers=None, boxprops=None, labels=None, flierprops=None, medianprops=None, meanprops=None, capprops=None, whiskerprops=None, manage_ticks=True, autorange=False, zorder=None, data=None)
18.
np.random.seed(10)
data = np.random.normal(50, 20, 100)
plt.boxplot(data)
plt.show()
19.
np.random.seed(10)
data_1 = np.random.normal(10, 10, 500)
data_2 = np.random.normal(80, 20, 500)
data_3 = np.random.normal(40, 30, 500)
data_4 = np.random.normal(70, 40, 500)
data = [data_1, data_2, data_3, data_4]
fg = plt.figure(figsize =(10, 7))
axis = fg.add_axes([0, 0, 1, 1])
bp = axis.boxplot(data)
- Working with images
We need to import matplotlib.image for working with images.
20.
import matplotlib.image as mpimg
img = mpimg.imread('DevIncept.png')
plt.imsave("logo.png", img, cmap = 'gray')
imgplot = plt.imshow(img)
And we can continue playing with these!
This contribution has been made by Prachi Agarwal. Contact me directly on my e-mail:[email protected] . Or ping me at, https://www.instagram.com/prachi_diwan21/ .