/  Matplotlib   /  Matplotlib tutorial with Python ## Matplotlib tutorial with Python

### Bar plots:

They are used to represent comparision between the data points using the bars either horizontally or vertically

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(4)
money = [1, 2, 5, 6]
plt.ylabel('Millions')
plt.xlabel('Top Tycoons')
plt.title('Richest in the World')
plt.bar(x, money)
plt.xticks(x, ('Gates', 'Warren', 'Mittal', 'Ambani'))
plt.show()


### Basic plotting

plt.plot([5, 20, 33, 12])
plt.show()
x=np.linspace(-np.pi, np.pi, 256, endpoint=True)
s, c=np.sin(x), np.cos(x)
plt.plot(x,c)
plt.plot(x,s)
plt.show()


COLOR CHANGE

Let us make few changes like figure size, color of lines, line width etc

using the function “figure”, “plot”

In the figure function we can provide the size of the image output details and dpi value

which is dots per inch to increase visual quality.

In the plot function , we can provide the line color and width for cos and sin curves.

plt.figure(figsize=(7,7), dpi=70,facecolor="blue")
plt.plot(x, c, color="green", linewidth=20, linestyle="-")


Note-Execute above 2 lines combined to see the output

plt.plot(x, s, color="black",  linewidth=5, linestyle="-")
plt.show()


### Ticks

In Matplotlib, ticks are generally displayed as small marks on both X and Y axis reference points for plotting the curves.

You can observe in our previous topic, the plot has 7 ticks on x axis and 9 ticks on Y axis.We can change those ticks using the xticks() and yticks() functions.

plt.figure(figsize=(7, 7), dpi=70)
plt.plot(x, c, color="green", linewidth=20, linestyle="-")
plt.plot(x, s, color="black",  linewidth=5, linestyle="-")

plt.xticks([-np.pi, 0, np.pi])
plt.yticks([-1, 0, +1])
plt.show()


### Tick labels

If you observe in the previous plot for ticks on X axis we have given -pi , 0 , pi which are represented in numerical format. But i want to print the labels as mathematical pi symbol.we have to use the latex to render the label as we required and we need provide those values in the second argument list of correspoding label.

plt.figure(figsize=(7, 7), dpi=70)
plt.plot(x, c, color="green", linewidth=20, linestyle="-")
plt.plot(x, s, color="black",  linewidth=5, linestyle="-")
plt.xticks([-np.pi, 0, np.pi],[r'$-\pi$',  r'$0$',  r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
plt.xlabel('x')
plt.ylabel('Degrees')
plt.show()


### Moving Spines

Spines are the lines which required to place at arbitrary positions that are connecting the axis tick marks and noting the boundaries. So, we have to move the lines or the axis behind our sin, cos curves where the left ones will be the negative values and right ones will be the positive values for X axis. For Y axis, negatives will be the down and positives will be on the upper side of the axis.

plt.figure(figsize=(10, 6), dpi=70)
plt.plot(x, c, color="green", linewidth=15, linestyle="-")
plt.plot(x, s, color="grey",  linewidth=10, linestyle="-")
ax = plt.gca() # to get the current axes, creating them if necessary.
ax.spines['right'].set_color('none') # making the top and right spine invisible.
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom') # moving bottom spine up to y=0 position
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left') # moving left spine to the right to position x == 0
ax.spines['left'].set_position(('data',0))
plt.xticks([-np.pi, 0, np.pi],[r'$-\pi$',  r'$0$',  r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
plt.show()


In Matplotlib, legend is a function which is used to place the legend on the axes. we can place the legend in various positions and can be placed either inside or outside of the chart or plot.In our example, let us add the legend in the upper right corner.

plt.figure(figsize=(10, 6), dpi=70)
plt.plot(x, c, color="green", linewidth=10, linestyle="-", label="cosine")
plt.plot(x, s, color="grey",  linewidth=10, linestyle="-", label="sine")
plt.legend(loc='upper left')
plt.title('Sine & Cos Function')
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.xticks([-np.pi, 0, np.pi],[r'$-\pi$',  r'$0$',  r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
plt.show()


### CONTOUR PLOT

Contour is nothing but the outlines or shape of something.Contour plots are isolines to represent the graphical 3-D surface by plotting the Z slices. Simply we can say that Contour plots can be used to show 3-Dimensional surfaces on a 2-Dimensional plane.

Syntax

• To create a contour plot of an array Z. The level values are taken automatically by itself.  contour(Z)
• To create a contour plot using the coordinates X, Y specify the (x, y) coordinates of the surface. contour(X,Y,Z)
• To contour up to N automatically-chosen levels. contour(X,Y,Z,N)
• To draw contour lines at specified values in sequence V in increasing order. contour(Z,V) ,contour(X,Y,Z,V)
• To fill the len(V)-1 regions between the values in V in increasing order. contourf(…, V)

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
return (1 + x*2+ x *1 + y * 3) * np.exp(-x ** 2 -y ** 2)
n = 0.01
x = np.arange(-3.0, 3.0, n)
y = np.arange(-2.0, 2.0, n)
X, Y = np.meshgrid(x, y)
plt.contourf(X, Y, f(X, Y), 8, alpha=.5, cmap='jet')
C = plt.contour(X, Y, f(X, Y), 8, colors='black')
plt.clabel(C, inline=1, fontsize=10)
plt.title('Simple Contour Plot with labels')
plt.show()


When we want to plot the numpy arrays which consists some data as images can be rendered using the function called imshow().

plt.imshow(f(X, Y))

### GRIDLINES

Creating the gridlines in the plot gives us the visualisation of coordinate points clearly.

matplotlib.pyplot.grid(b=None, which=’major’, axis=’both’, **kwargs)¶

You can always turn the axes grids on or off by passing the argument b which is a boolean value.

Now let us add the grid lines to the quiver plot

import matplotlib.pyplot as plt
import numpy as np
x,y = np.meshgrid(np.arange(0, 2*np.pi, .2), np.arange(0, 2*np.pi, .2))
u = np.cos(y)
v = np.sin(x)
plt.figure()
plt.quiver(x, y, u, v, scale=4, pivot='tip', units='x')
plt.scatter(x, y, color='r', s=10)
plt.grid(color='b', linestyle='-', linewidth=0.5)
plt.show()


### Pie plot

Pie plot is a kind of graphical representation in which a circle is divided into slices, where each slice represents a numeric proportion of entire circle.

Syntax

matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6,

textprops=None, center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None)

import matplotlib.pyplot as plt
#In this Pie chart, slices will be plotted counter-clockwise.
labels = 'Mathematics', 'Physics', 'Chemistry', 'Biology'
sizes = [40, 20, 25, 15]
explode = (0.1, 0, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
# Equal makes up a circle.
plt.axis('equal')
plt.show()
#Let us add a legend to the above pie chart with the help of plt.legend() function.
labels = 'Mathematics', 'Physics', 'Chemistry', 'Biology'
sizes = [40, 20, 25, 15]
explode = (0.1, 0, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
# Equal makes up a circle.
plt.axis('equal')
plt.legend(labels, loc="best")
plt.show()


### QUIVER PLOT

Quiver plot is used to display velocity vectors as arrows with components (u,v)

at the points (x,y).

Syntax:

#Axes.quiver(*args, data=None, **kw)

Calling with different arguements

• quiver(U, V, **kw)
• quiver(U, V, C, **kw)
• quiver(X, Y, U, V, **kw)
• quiver(X, Y, U, V, C, **kw)
• U, V – Represents the Arrow data.
• X, Y – Represents location of arrows.
• C    – Represents the Color of arrows.

import matplotlib.pyplot as plt
import numpy as np
x,y = np.meshgrid(np.arange(0, 2*np.pi, .2), np.arange(0, 2*np.pi, .2))
u = np.cos(y)
v = np.sin(x)
plt.figure()
plt.quiver(x, y, u, v, scale=4, pivot='tip', units='x')
plt.scatter(x, y, color='r', s=5)
plt.show()


### REGULAR PLOT

In this tutorial, we will discuss all about how to create a regular plot in matplotlib

import matplotlib.pyplot as plt
import numpy as np
#Here fill_between() function takes color, axis, alpha as arguments in the below code.
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
Y = np.sin(2*X)
plt.plot(X, Y + 1, color='blue', alpha=1.00)
plt.fill_between(X,6, Y + 1, color='orange', alpha=0.7) #here 6 is max value to fill, alpha shows the level of shaded region.
plt.plot(X, Y - 1, color='blue', alpha=1.00)
plt.fill_between(X,-4, Y-1, color='red', alpha=0.6)
plt.show()


Below are the supported color abbreviations:

character             color

• ‘b’                         blue
• ‘g’                          green
• ‘r’                          red
• ‘c’                          cyan
• ‘m’                        magenta
• ‘y’                          yellow
• ‘k’                          black
• ‘w’                        white

### SCATTER PLOTS

Scatter plots are just like regular line graphs which uses the X and Y axes to plot the input data. It is used in situations where we want to show the correlation between one and another.

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=None, edgecolors=None, hold=None, data=None, **kwargs)

Here, s represents the Marker Size and c represents the marker color.

import matplotlib.pyplot as plt
import numpy as np
n =100
X = np.random.normal(0,1,n) # To draw random samples from a normal (Gaussian) distribution with Mean=0 and SD=1.
Y = np.random.normal(0,1,n)
col=np.random.rand(n)
plt.scatter(X, Y, s=520, alpha=.6,c=col)
plt.xlim(-1.5, 1.9)
plt.xticks(())
plt.ylim(-1.5, 1.5)
plt.yticks(())
plt.show()


### SUBPLOTS

Using the subplots, we can divide an area into multiple subplots in a grid.

We can do this by specifying the number of rows and columns and the number of plot.Here x and y must have same first dimension otherwise we get error.

import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig,ax = plt.subplots(nrows=2, ncols=2) #Here fig should be mentioned.
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
#Another way to show the same subplots
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
plt.subplot(2, 2, 1) # It i equalent to plt.subplot(221)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.subplot(2, 2, 4)
plt.plot(x, y)
plt.show()


### Axes function

#Many people confuse here with axes with axis. Axes is different than axis in matplotlib. Axis represents the x-axis or the y-axis where as the axes means it is mostly like a subplots which will allow the placement of those plots in any location within the figure or plot. We can keep a small plot with in a bigger one or we can place two small plots side by side with in the figure.

plt.axes([.1, .1, .5, .5])
plt.xticks(())
plt.yticks(())
plt.text(0.1, 0.9, 'axes([0.1, 0.1, .8, .8])', ha='left', va='top',
size=16, alpha=.5)#ha means horizontal alignment
# x=0.1 is x coordinate, 0 leftmost positioned, 1 rightmost
# the text which will be printed is axes([0.1, 0.1, .8, .8])
plt.axes([.2, .2, .5, .5])
plt.xticks(())
plt.yticks(())
plt.text(0.1, 0.1, 'subplot(1,2,3)', ha='left', va='center',
size=16, alpha=.5)


plt.show()