Matplotlib In Python: A Tutorial In 3 Simple Points

Introduction

Images are a powerful means of communication. We often use them to better understand the situation or to wrap pieces of information into a graphic image. To give a few examples of how they can help, let us consider the fields of scientific analysis and practice. To clearly identify the issues, it is very important to be able to visualize the data when analyzing performance data. Similarly, just looking at a graph drawn for scientific research can give a scientist a better understanding of the results.

Python is a translated language with a strong core function and a powerful modular feature that allows you to expand the language with external modules that provide new functionality. The result is that we have a flexible language with the tools to accomplish one task in the best possible way. Modules are usually packaged. A package is a structured set of modules with the same purpose. One example of a package is Matplotlib in Python.

  1. What is Matplotlib in Python?
  2. What is Matplotlib in Python used for?
  3. Python Matplotlib – Types of Plots

1. What is Matplotlib in Python?

Matplotlib is a 2D editing python package that produces quality production graphs in python. It supports collaborative and non-interactive editing and can save images in multiple output formats. It permits easy installation of various plots in python, including line, scatter, bar, and radial sites, with high flexibility for improved style.

The flexible artist module allows developers to basically define any type of visualization. For general use, Matplotlib in python provides an easy-to-use interface, a matplotlib pyplot module, for easy plotting.

Matplotlib in python is easily integrated into development environments, such as Jupyter Notebook, and supports many advanced data viewing packages.

2. What is Matplotlib in Python used for?

Matplotlib is a python library used for plotting. The object-focused module simplifies the plotting process. We only need to call to import maplotlib.pyplot as plt import API to build and customize many basic matplotlib plots.

For styling, Matplotlib in python offers functions to change the look of each element, and ready-made style sheets are available to avoid these additional steps when adjusted aesthetics are not required.

3. Python Matplotlib – Types of Plots

1. Matplotlib Histogram: Histograms are useful in surveying the distribution of data. In Matplotlib, we call the plt.hist ( ) function with a linear array. Matplotlib in python automatically group the set of data points into bins and plot out the frequencies for each bin in bars.

Here is an example of plotting a randomly generated binomial distribution:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. np.random.seed ( 8 )
  4. x = np.random.binomial (100, 0.5, size=10000 )
  5. plt.hist (x, bins=20 ) # or plt.hist (x, 20 )
  6. plt.show ( )

The histogram produced is as follows:

2. Bar plot Matplotlib: Bar plots are useful for comparing absolute levels of discrete data series. They are created by the function plt.bar ( labels, heights ) in Matplotlib.

Let’s look at the example of the market capitalization of five top cryptocurrencies:

  1. import matplotlib.pyplot as plt
  2. cc = [ ‘BTC’, ‘XRP’, ‘ETH’, ‘BCH’, ‘ADA’ ]
  3. cap = [ 282034, 131378, 107393, 49999, 26137]
  4. plt.bar ( cc, cap )
  5. plt.title ( ‘Market Capitalization of five top cryptocurrencies in Jan 2018’ )
  6. plt.xlabel ( ‘cryptocurrency’ )
  7. plt.ylabel ( ‘Market capitalization (million USD)’ )
  8. plt.show ( )

Output:

3. Pie Chart: Pie Chart is a circular representation of component ratios. The angle, and hence the arc length of eachsector ratio (also called wedges), presents the proportion that each component accounts for, relative to the whole.

Matplotlib in python provides the plt.pie ( ) function to draw pie charts. We can label each sector with labels as well as the percentage with autopct automatically. To maintain the circular shape of the pie chart, we specify the same width and length for a square figure with plt.figure ( figsize= ( n, n ) ).

Let’s take an example of web server usage:

  1. import matplotlib.pyplot as plt
  2. plt.figure ( figsize= ( 4, 4 ) )
  3. x = [ 0.31, 0.3, 0.14, 0.1, 0.15 ]
  4. labels = [ ‘nginx’, ‘Apache’, ‘IIS’, ‘Varnish’, ‘Others’ ]
  5. plt.pie ( x, labels= labels, autopct= ‘%1.1f %%’ )
  6. plt.title ( ‘Web Server Usage Statistics’ )
  7. plt.show ( )

Output:

4. Matplotlib Scatter Plot: Another basic plot type is a scatter plot, a plot of dots. You can draw it by calling plt.scatter ( x, y ). The following example shows a scatter plot of random dots:

  1. import NumPy as np
  2. import matplotlib. pyplot as plt
  3. np. random.seed ( 42 ) 
  4. r = np.random.rand ( 2, 100 ) 
  5. plt.scatter ( r [0], r [1] )
  6. plt.show ( )

5. Error Bar Charts: In experimental sciences, we know that all the measurements that we take lack perfect precision. This leads to repeating the measurements, which results in obtaining a set of values. The expected result is that all those measures group up around the true value that we want to measure.

The representation of this distribution of data values is done by plotting a single data point, (commonly) the mean value of the dataset, and an error bar to represent the overall distribution of data. This helps us to get a general idea of how accurate a measurement is ( or how far the reported value could be from the error-free value ).

Using the errorbar ( ) function, Matplotlib in python allows us to create such a graph type.

Let’s take an example:

  1. import matplotlib.pyplot as plt
  2. import NumPy as np
  3. x = np.arange ( 0,  4,  0.2 )
  4. y = np.exp ( -x )
  5. el = 0.1 * np.abs ( np.random.randn ( len (y ) ) )
  6. plt.errorbar ( x, y, yerr=el, fmt= ‘.-‘ );
  7. plt.show ( )

Conclusion

The idea behind Matplotlib can be summed up in the following motto as quoted by John Hunter, the creator and project leader of Matplotlib:

“Matplotlib tries to make easy things easy and hard things possible”.

If you want to learn more about Java then check out Jigsaw Academy’s Master Certificate In Full Stack Development – a 170 hour-long live online course. It is the first & only program on Full Stack Development with Automation and AWS Cloud. Happy learning!

ALSO READ

Related Articles

} }
Request Callback