Reader small image

You're reading from  Matplotlib 3.0 Cookbook

Product typeBook
Published inOct 2018
PublisherPackt
ISBN-139781789135718
Edition1st Edition
Right arrow
Authors (2):
Srinivasa Rao Poladi
Srinivasa Rao Poladi
author image
Srinivasa Rao Poladi

Srinivasa Rao Poladi has been in the IT services industry for over two decades, providing consulting and implementation services in data warehousing, business intelligence, and machine learning areas for global customers. He has worked with Wipro Technologies for two decades and played key leadership roles in building large technology practices and growing them to multi-million $ business. He spoke at international conferences, published many blogs and white papers in the areas of big data, business intelligence, and analytics. He is a co-founder of krtrimaIQ a consulting firm that provides cognitive solutions to create tomorrow's Intelligent Enterprises powered by automation, big data, machine learning, and deep learning.
Read more about Srinivasa Rao Poladi

Nikhil Borkar
Nikhil Borkar
author image
Nikhil Borkar

Nikhil Borkar holds a CQF designation and a post Graduate Degree in Quantitative finance. He also holds the Certified Financial Crime examiner and Certified Anti-Money Laundering Professional qualifications. He is a registered Research Analyst with the Securities and Exchange Board of India (SEBI) and has a keen grasp of the Indian regulatory landscape pertaining to Securities and Investments. He is currently working as an independent FinTech and legal consultant. Prior to this, the worked with Morgan Stanley Capital International (MSCI) as a Global RFP Project Manager.
Read more about Nikhil Borkar

View More author details
Right arrow

Plotting 3D Graphs Using the mplot3d Toolkit

In this chapter, we will cover the recipes for plotting the following graphs:

  • Line plot
  • Scatter plot
  • Bar plot
  • Polygon plot
  • Contour plot
  • Surface plot
  • Wireframe plot
  • Triangular surface plot
  • Plotting 2D data in 3D
  • 3D visualization of linearly non-separable data in 2D
  • Plotting word embeddings

Introduction

Early versions of Matplotlib were limited to 2D plotting, and 3D features were added later as an add-on toolkit: mplot3d. Although it has limited 3D functionality, it covers most of the common business requirements of 3D plotting.

Plotting commands are similar to their 2D counterparts. It is just that we register with Matplotlib that we will be using 3D plots, by importing Axes3D from the mplot3d toolkit, and in the axes definition, we specify projection='3d'.

You can also rotate the 3D picture to get different views, if you are using any of the interactive backends, by dragging the figure in any direction you want. You can also create an animation by rotating the figure with a small pause in between the frames. We will learn how to use these features in some of the plots, although they can be applied to all plots.

...

Line plot

In this recipe, we will learn how to create a 3D line plot. It is similar to a 2D equivalent line plot, and many of the attributes of a 2D line plot are carried forward to 3D.

We will draw concave and convex curves in the same axes and view them from different angles, such as parallel view, top view, and rotation around the z axis.

Getting ready

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

How to do it...

Here are the steps to plot 3D line graphs:

  1. Prepare the data for the x, y, and z...

Scatter plot

In this recipe, we will learn how to plot a scatter plot in 3D. We will use the Iris dataset, which has three distinct clusters, for this example. We have seen it in 2D several times in previous chapters, so let's see how it looks in 3D.

We will also learn how to create an animated 3D plot using the init_view method that we learned in the preceding recipe. For this, we need to use any of the backends, since animation does not work with the inline display %matplotlib inline.

Getting ready

Set the desired backend:

import matplotlib
matplotlib.use('tkAgg')

Import the required libraries:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
...

Bar plot

In this recipe, we will learn how to plot a bar graph in 3D. We will use the battery sales data that we used for table plotting in Chapter 2, Getting Started with Basic Plots. Here, we will only plot a bar chart, not the table chart, below the bar graph.

Getting ready

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

How to do it...

The following are the steps to implement the logic:

  1. Define the figure and axes for 3D plotting:
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111, projection...

Polygon plot

In this recipe, we will learn how to plot a polygon plot. It is similar to a line plot, but filled under the line. We will use the same battery sales data for this example also.

Getting ready

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
from matplotlib.ticker import MultipleLocator

How to do it...

Here are the steps to code the logic:

  1. Define the figure and axes for 3D plotting:
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111...

Contour plot

We learned how to draw a 2D contour plot in Chapter 2, Getting Started with Basic Plots. Here, we will learn how to draw it in 3D. We will use the same data that we used earlier, so that we can see the difference between 2D and 3D visualization.

Getting ready

Import the required libraries:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import cm

How to do it...

Here are the steps to create the desired plot:

  1. Define the figure and axes for 3D plotting:
fig = plt.figure(figsize=(10,8))
ax = fig.gca(projection...

Surface plot

In this recipe, we will learn how to draw a surface plot. This is typically used to visualize the loss (error) surface in machine-learning problems. It helps to see whether the algorithm is stuck in any local minima, when the error surface has multiple minima. We will use the same data that we used in the preceding contour plot.

Getting ready

Import the required libraries:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

How to do it...

The following are the steps to draw a surface plot:

  1. Define the...

Wireframe plot

In this recipe, we will learn how to draw a wireframe plot. It is similar to a surface plot, with the option of sampling a number of points in each of the directions to connect on the surface. Here, we will implement an animated wireframe plot.

Getting ready

Set the desired backend for the interactive output:

import matplotlib
matplotlib.use('Qt5Agg')

Import the required libraries:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

How to do it...

Here are the steps involved in drawing a wireframe plot:

  1. Define...

Triangular surface plot

In this recipe, we will learn how to draw a triangular surface plot. It is similar to surface plot, but the surface will have triangular connections. We will draw three such plots with different data, and with and without the axes being shown.

Getting ready

Import the required libraries:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

How to do it...

The following are the steps to draw triangular surface plots:

  1. Prepare data for three different plots:
# Make radii and angles arrays.
radii = np.linspace(0...

Plotting 2D data in 3D

In this recipe, we will learn how we can plot 2D data in 3D. We will plot product defects by reason code as a bar plot, and cumulative defects as a line plot. We will have defect reason codes on the x axis, the number of defects on the z axis, and cumulative defect percentage on the y axis. There are kind of two y axes in 2D space, where one of them will have the scale for the bar graph and the other will have the scale for the line graph.

Getting ready

Import the required libraries:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

How to do it...

...

3D visualization of linearly non-separable data in 2D

In this recipe, we will learn how we can visualize 2D data that is linearly non-separable in 3D. This is typically used to explain the internal workings of the Support Vector Machines algorithm, which takes lower dimensional data to higher dimensional space so that it can find a plane that separates the data into various clusters neatly.

We will plot both 2D and 3D plots with the same data to visualize it better.

Getting ready

Import the required libraries:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

How to do it...

Word embeddings

In Chapter 7, Embedding Text and Expressions, we learned how to plot word embeddings in 2D space. Here, we will learn how to plot the same word embeddings in 3D space. To create the required data, we will have to run t-SNE algorithm with three components to generate x, y, and z coordinates. We will use this output to plot the graph.

Getting ready

Import the required libraries:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pickle

How to do it...

Here are the steps involved in plotting a word embeddings graph:

  1. Load the required...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Matplotlib 3.0 Cookbook
Published in: Oct 2018Publisher: PacktISBN-13: 9781789135718
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Srinivasa Rao Poladi

Srinivasa Rao Poladi has been in the IT services industry for over two decades, providing consulting and implementation services in data warehousing, business intelligence, and machine learning areas for global customers. He has worked with Wipro Technologies for two decades and played key leadership roles in building large technology practices and growing them to multi-million $ business. He spoke at international conferences, published many blogs and white papers in the areas of big data, business intelligence, and analytics. He is a co-founder of krtrimaIQ a consulting firm that provides cognitive solutions to create tomorrow's Intelligent Enterprises powered by automation, big data, machine learning, and deep learning.
Read more about Srinivasa Rao Poladi

author image
Nikhil Borkar

Nikhil Borkar holds a CQF designation and a post Graduate Degree in Quantitative finance. He also holds the Certified Financial Crime examiner and Certified Anti-Money Laundering Professional qualifications. He is a registered Research Analyst with the Securities and Exchange Board of India (SEBI) and has a keen grasp of the Indian regulatory landscape pertaining to Securities and Investments. He is currently working as an independent FinTech and legal consultant. Prior to this, the worked with Morgan Stanley Capital International (MSCI) as a Global RFP Project Manager.
Read more about Nikhil Borkar