Codementor Events

Matplotlib tutorial (Plotting Graphs Using pyplot)

Published Feb 06, 2020
Matplotlib tutorial (Plotting Graphs Using pyplot)

Matplotlib is a library in python that creates 2D graphs to visualize data. Visualization always helps in better analysis of data and enhance the decision-making abilities of the user. In this matplotlib tutorial, we will plot some graphs and change some properties like fonts, labels, ranges, etc,

First, we will install matplotlib, then we will start plotting some basics graphs. Before that, let’s see some of the graphs that matplotlib can draw.

Plot Types

There are a number of different plot types in matplotlib. This section briefly explains some plot types in matplotlib.

Line Plot

A line plot is a simple 2D line in the graph.

Contouring and Pseudocolor

We can represent a two-dimensional array in color by using the function pcolormesh() even if the dimensions are unevenly spaced. Similarly, the contour()  function does the same job.

Histograms

To return the bin counts and probabilities in the form of a histogram, we use the function hist().

Paths

To add an arbitrary path in Matplotlib we use matplotlib.path module.

Streamplot

We can use the streamplot() function to plot the streamlines of a vector. We can also map the colors and width of the different parameters such as speed time etc.

Bar Charts

We can use the bar() function to make bar charts with a lot of customizations.

Other Types

Some other examples of plots in Matplotlib include:

  • Ellipses
  • Pie Charts
  • Tables
  • Scatter Plots
  • GUI widgets
  • Filled curves
  • Date handling
  • Log plots
  • Legends
  • TeX- Notations for text objects
  • Native TeX rendering
  • EEG GUI
  • XKCD-style sketch plots

Installation

Assuming that the path of Python is set in environment variables, you just need to use the pip command to install matplotlib package to get started.

Use the following command:

$ pip install matplotlib

In my system, the package is already installed. If the package isn’t already there, it will be downloaded and installed.

To import the package into your Python file, use the following statement:

import matplotlib.pyplot as plt

Where matplotlib is the library, pyplot is a package that includes all MATLAB functions to use MATLAB functions in Python.

Finally, we can use plt to call functions within the python file.

Vertical Line

To plot a vertical line with pyplot, you can use the axvline() function.

The syntax of axvline is as follows:

plt.axvline(x=0, ymin=0, ymax=1, \*\*kwargs)

In this syntax: x is the coordinate for x axis. This point is from where the line would be generated vertically. ymin is the bottom of the plot, ymax is the top of the plot. **kwargs are the properties of the line such as color, label, line style, etc.

import matplotlib.pyplot as plt

plt.axvline(0.2, 0, 1, label='pyplot vertical line')

In this example, we draw a vertical line. 0.2 means the line will be drawn at point 0.2 on the graph. 0 and 1 are ymin and ymax respectively.

label one of the line properties. legend() is the MATLAB function which enables label on the plot. Finally, show() will open the plot or graph screen.

Horizontal Line

The axhline() plots a horizontal line along. The syntax to axhline() is as follows:

plt.axhline(y=0, xmin=0, xmax=1, \*\*kwargs)

In the syntax: y is the coordinates along y axis. These points are from where the line would be generated horizontally. xmin is the left of the plot, xmax is the right of the plot. **kwargs are the properties of the line such as color, label, line style, etc.

Replacing axvline() with axhline() in the previous example and you will have a horizontal line on the plot:

import matplotlib.pyplot as plt

plt.axhline(ypoints, 0, 1, label='pyplot horizontal line')

Multiple Lines

To plot multiple vertical lines, we can create an array of x points/coordinates, then iterate through each element of array to plot more than one line:

import matplotlib.pyplot as plt

xpoints = [0.2, 0.4, 0.6]

    plt.axvline(p,  label='pyplot vertical line')

The above output doesn’t look really attractive, we can use different colors for each line as well in the graph.

Consider the example below:

import matplotlib.pyplot as plt

xpoints = [0.2, 0.4, 0.6]

for p, c in zip(xpoints, colors):

    plt.axvline(p,  label='line: {}'.format(p), c=c)

In this example, we have an array of lines and an array of Python color symbols. Using the zip() function, both arrays are merged together: the first element of xpoints[] with the first element of the color[] array. This way, first line = green, second line = cyan, etc.

The braces {} act as a place holder to add Python variables to printing with the help of the format() function. Therefore, we have xpoints[] in the plot.

Just replace the axvline() with axhline() in the previous example and you will have horizontal multiple lines on the plot:

import matplotlib.pyplot as plt

ypoints = [0.2, 0.4, 0.6, 0.68]

colors = ['b', 'k', 'y', 'm']

for p, c in zip(ypoints, colors):

    plt.axhline(p,  label='line: {}'.format(p), c=c)

The code is the same, we have an array of four points of y axis and different colors this time. Both arrays are merged together with zip() function, iterated through the final array and axhline() plots the lines as shown in the output below:

Save Figure

After plotting your graph, how to save the output plot?

To save the plot, use savefig() of pyplot.

plt.savefig(fname, \*\*kwargs)

Where fname is the name of the file. The destination or path can also be specified along with the name of the file. The kwargs parameter is optional. It’s used to change the orientation, format, facecolor, quality, dpi, etc.

Discover and read more posts from LikeGeeks
get started
post commentsBe the first to share your opinion
Show more replies