# Plotting Tutorial in Python with Matplolib.pyplot – Part 1 In this practical lesson, I would teach you how to plot in Python. You will learn about plotting in Python with Matplotlib.pyplot.

So, we’ll cover the following topics. Watch the video lesson

##### 1. Introduction

Matplotlib is a Python module for 2D plotting and the matplotlib.pyplot sub-module contains many plotting functions to create various kinds of plots. So we begin  by importing matplotlib.pyplot and using %matplotib Jupyter magic to display plots in the notebook.

Before you can plot, you need to import the neccessary modules. You do that using the code below:

```# you need to import numpy and pyplot
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```

##### 2. Basic Plotting

Let’s look at how to create a basic 2D plot. The procedure is:

• Create a sequence that represents x values.
• Create a sequence the represents the y values.
• Use plt.plot(x,y,[fmt],**kwargs). [fmt] is an (optional) format string while **kwargs are also (optional) keyword arguments the specifies the line properties of the plot.
• Use pyplot functions to add features to the plot such as gridlines,  title, legend, etc.
• Use plt.show() to display the resulting figure.

Example i, the code below, produces the line plot shown

```x = [-6, -5, -2, 0, 1, 3, 4]
y = [1, 2, -1, 1, -4, 3, 2]

plt.plot(x,y)
plt.show()
``` Example ii, a second plot. But notice the  that the edges of the curve are sharp edges.

```x = [-3, -2, -1, 0, 1, 2, 3]
y =[5, 4,1, 0,1,4, 5]

plt.plot(x, y)
plt.show()
``` Example iii, now we would plot a smooth curve by using a larger number of points. The code and curve are shown below

```# Smooth curve is produced by using large number of data points
x = np.linspace(-3,3,200)
y = x**2

plt.plot(x, y)
plt.show()
``` Now, you know how to create basic plots, let’s now see how to format our plot.

##### 3. Properties of a Line

Some of the properties of the line you can set includes, color, alpha(transparency), style, width, markers etc. These properties can be set by giving additional attributes to the plot method. The table below shows that attributes you can use to format your plot

 Property Description alpha (transparency) transparency (0.0 transparent through 1.0 opaque) color (or c) any matplotlib color label text appearing in legend linestyle (or ls) solid, dashed, dashdot, dotted linewidth (or lw) set width of the line marker set marker style markeredgecolor (or mec) any matplotlib color markerfacecolor (or mfc) any matplotlib color markersize (or ms) size of the marker

Table 1: Properties of a Plot  Line

We would apply what we learnt to plot a curve. The curve would be the damped cosine wave curve based on this function You should learn how to write math functions in Python format. For example the equation in Python will be:
y = np.exp(-x**2) * np.cos(2 * np.pi * x)

I guess I’ll cover this in another tutorial.

The complete code is given below. Notice how we have used the attributes specified in Table 1 to set the properties of the curve.

```#generate a sequence of 40 values from -2 to 2
x = np.linspace(-2,2,40)
y = np.exp(-x**2)* np.cos(2*math.pi*x) #damped cosine wave

plt.plot(x,y,
alpha=0.4,
label='Damped Cosine Wave',
color='red', linestyle='dashed',
linewidth=2,
marker='*',
markersize=7,
markerfacecolor='red',
markeredgecolor='blue')
plt.ylim([-2,2])
plt.legend()
plt.show()
```

If you run the code, the resulting curve will be I recommend, you change of some of the attributes in the code and see how it affects the curve

We can you a format string to shortcut to add attributes like color, marker, and linestyle to a line plot. For instance, assuming we want to plot the The equivalent Python code is given below

```x = np.linspace(-5,5,40)
y = 1/(1 + x**2)
plt.plot(x, y,
color='red',
marker='s',
markerfacecolor='blue')
plt.show()
``` The code below also achieves the same thing

```x = np.linspace(-5,5,40)
y = 1/(1 + x**2)
plt.plot(x, y,
'rs--',
markerfacecolor='blue')
plt.show()
```

In the code above, ‘rs—‘ means:

• r stands for a red line
• s stands for a square marker
• — stands for a dashed line

The tables below give the the shortcuts for other attributes

Shortcuts for colors

 Character Color b blue g green r red c cyan m magenta y yellow k black w white

Shortcuts for markers

 Character Marker . point o circle v triangle down ^ triangle up s square p pentagon * star + plus x x D diamond

Shortcuts for linestyles

 Character Line Style – solid line style — dashed line style -. dash-dot line style : dotted line style
##### 5. Pyplot Functions

There are a number of pyplot functions available for us to customize our figures. For example, the table below shows some of them:

 Fucntion Description plt.xlim sets the x limits plt.ylim sets the  y limits plt.grid adds the grid lines plt.title adds a title plt.xlabel adds a label to the horizontal axis plt.ylabel adds a label to the vertical axis plt.axis sets axis properties (equal, off, scaled, etc.) plt.xticks sets tick locations on the horizontal axis plt.yticks sets tick locations on the vertical axis plt.legend displays legend for several lines in the same figure plt.savefig save figure (as .png, .pdf, etc.) to working directory plt.figure creates a new figure and set its properties

Let’s now apply some of these pyplot functions to create a plot.

##### 6. Example 1 – Plotting the Taylor’s Polynomial

Now, we are going to used some the pyplot functions to plot the Taylor’s Polynomial.

This is also called Taylor’s Series and it is a way to represent  a function as an infinite sum of terms that are computed from the values of the function’s derivatives at a single point.

```##################### EXAMPLE 1 - TAYLOR'S POLYNOMIAL #######################

# Generate a sequence of 50 values from -6 to 6
x = np.linspace(-6, 6, 50)

# Plot y = cos(x)
y = np.cos(x)
plt.plot(x, y, 'b', label='cos(x) ', lw=3) #black line

# Plot order 2 of Taylor's polynomial
y2 = 1 - x**2/2
plt.plot(x, y2, 'r-.', label='Degree 2', lw=3) #red line

# Plot order 4 of Taylor's polynomial
y4 = 1 - x**2/2 + x**4/24
plt.plot(x, y4, 'g:', label = 'Degree 4', lw=3) #green line

#Add some features to the figure
plt.legend()
plt.grid(True, linestyle=':')
plt.xlim(-6, 6)
plt.ylim(-4, 4)
plt.title('Taylors Polynomial of cos(x) at x=0')
plt.xlabel('x values')
plt.ylabel('y value')
plt.show()
```

The output of the code is the graph shown below: Now that you have completed Part 1 of Plotting Tutorial in Python with Matplolib.pyplot, thumbs up to you! You can now proceed to Part 2.

### 2 Comments on “Plotting Tutorial in Python with Matplolib.pyplot – Part 1”

1. hatch sandwich bar says:

I simply couldn’t go away your site before suggesting that
I extremely loved the standard information an individual provide on your guests?
Is going to be again ceaselessly to inspect new posts