INTRODUCTION TO MATPLOTLIB

Ravi shankar
6 min readJul 5, 2021

--

Matplotlib

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter notebook, web application servers, and four graphical user interface toolkits.

  • Matplotlib is the most popular plotting library for python.
  • It gives you control over every aspect of a figure.
  • It was designed to have a similar feel to Matlab’s graphical plotting.

Installation

python -mpip install -U matplotlib

Importing matplotlib :

from matplotlib import pyplot as plt
or
import matplotlib.pyplot as plt

Matplotlib.figure.Figure()

This class is the top level container for all the plot elements.

import matplotlib.pyplot as plt

from matplotlib.figure import Figure

import numpy as np

fig = plt.figure(figsize =(5, 4))

ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

xx = np.arange(0, 2 * np.pi, 0.01)

ax.plot(xx, np.sin(xx))

fig.suptitle('matplotlib.figure.Figure() class Example\n\n',

fontweight ="bold")

plt.show()

axes.plot()

This is the basic method of axes class that plots values of one array versus another as lines or markers. The plot() method can have an optional format string argument to specify color, style and size of line and marker.

import matplotlib.pyplot as plt
y = [1, 4, 9, 16, 25,36,49, 64]
x1 = [1, 16, 30, 42,55, 68, 77,88]
x2 = [1,6,12,18,28, 40, 52, 65]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
l1 = ax.plot(x1,y,'ys-') # solid line with yellow colour and square marker
l2 = ax.plot(x2,y,'go--') # dash line with green colour and circle marker
ax.legend(labels = ('tv', 'Smartphone'), loc = 'lower right') # legend placed at lower right
ax.set_title("Advertisement effect on sales")
ax.set_xlabel('medium')
ax.set_ylabel('sales')
plt.show()

Artist

Artist is a 2D plotting library for Python. It’s main focus is the output

for intallation-

pip install artist

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
fig.subplots_adjust(top=0.8)
ax1 = fig.add_subplot(211)
ax1.set_ylabel('volts')
ax1.set_title('a sine wave')

t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
line, = ax1.plot(t, s, color='blue', lw=2)

# Fixing random state for reproducibility
np.random.seed(19680801)

ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])
n, bins, patches = ax2.hist(np.random.randn(1000), 50,
facecolor='yellow', edgecolor='yellow')
ax2.set_xlabel('time (s)')

plt.show()

Create Labels for a Plot

With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- and y-axis.

Example

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.plot(x, y)

plt.xlabel(“Average Pulse”)
plt.ylabel(“Calorie Burnage”)

plt.show()

Matplotlib Adding Grid Lines

With Pyplot, you can use the grid() function to add grid lines to the plot.

Example

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title(“Sports Watch Data”)
plt.xlabel(“Average Pulse”)
plt.ylabel(“Calorie Burnage”)

plt.plot(x, y)

plt.grid()

plt.show()

Create a Title for a Plot

With Pyplot, you can use the title() function to set a title for the plot.

Example

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.plot(x, y)

plt.title(“Sports Watch Data”)
plt.xlabel(“Average Pulse”)
plt.ylabel(“Calorie Burnage”)

plt.show()

Ticklabels

You can use the fontdict parameter in xlabel(), ylabel(), and title() to set font properties for the title and labels.

Example

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

font1 = {‘family’:’serif’,’color’:’blue’,’size’:20}
font2 = {‘family’:’serif’,’color’:’darkred’,’size’:15}

plt.title(“Sports Watch Data”, fontdict = font1)
plt.xlabel(“Average Pulse”, fontdict = font2)
plt.ylabel(“Calorie Burnage”, fontdict = font2)

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

line plots

import matplotlib.pyplot as plt
import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 1, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 1, 2)
plt.plot(x,y)

plt.show()

Matplotlib Bars

Creating Bars

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

Example

Draw 4 bars:

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()

Creating Pie Charts

With Pyplot, you can use the pie() function to draw pie charts:

Example

A simple pie chart:

import matplotlib.pyplot as plt
import numpy as np

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

plt.pie(y)
plt.show()

Histogram

The hist() function will read the array and produce a histogram:

Example

A simple pie chart:

import matplotlib.pyplot as plt
import numpy as np

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

plt.hist(x)
plt.show()

Box plot

# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = ax.boxplot(data_to_plot)
plt.show()

Bubble Plot

import matplotlib.pyplot as plt
import numpy as np

# create data
x = np.random.rand(40)
y = np.random.rand(40)
z = np.random.rand(40)
colors = np.random.rand(40)
# use the scatter function
plt.scatter(x, y, s=z*1000,c=colors)
plt.show()

Stacked Plot

# importing package

import matplotlib.pyplot as plt

# create data

x = ['A', 'B', 'C', 'D']

y1 = [10, 20, 10, 30]

y2 = [20, 25, 15, 25]

# plot bars in stack manner

plt.bar(x, y1, color='r')

plt.bar(x, y2, bottom=y1, color='b')

plt.show()

Table Chart

import matplotlib.pyplot as plt

val1 = ["{:X}".format(i) for i in range(10)]

val2 = ["{:02X}".format(10 * i) for i in range(10)]

val3 = [["" for c in range(10)] for r in range(10)]

fig, ax = plt.subplots()

ax.set_axis_off()

table = ax.table(

cellText = val3,

rowLabels = val2,

colLabels = val1,

rowColours =["palegreen"] * 10,

colColours =["palegreen"] * 10,

cellLoc ='center',

loc ='upper left')

ax.set_title('matplotlib.axes.Axes.table() function Example',

fontweight ="bold")

plt.show()

Polar Chart

mport numpy as np

import matplotlib.pyplot as plt

# setting the axes projection as polar

plt.axes(projection = 'polar')

# setting the radius

r = 2

# creating an array containing the

# radian values

rads = np.arange(0, (2 * np.pi), 0.01)

# plotting the circle

for rad in rads:

plt.polar(rad, r, 'g.')

# display the Polar plot

plt.show()

--

--

No responses yet