3D line plot in python

3D line plot in python using matplotlib

Image for post

There are many ways for doing 3D plots in python, here I will explain line plot using matplotlib. Like how to create an empty mesh and create a line plot graph using random data.

First, we have to install matplotlib to import the mplot3d toolkit. Mplot3d is a toolkit which will help for matplotlib to generate 3 axes on the graph.In case If you don?t have already installed matplotlib then its important to install matplotlib.

Plot 2D or 3D data.Axes3D.plot(xs, ys, *args, **kwargs)Argument Descriptionxs, ys x, y — coordinates of verticeszs z — value(s), either one for all points or one for each point.zdir — Which direction to use as z (?x?, ?y? or ?z?) when plotting a 2D set.

How to install matplotlib through pip ?

pip install matplotlib

copy this above command and put it into your python console and press enter.

if you have already installed matplotlib then you don?t need to install it again just import it using below command

imoprt matplotlib as plt

How to import mplot3d module from matplotlib?

from mpl_toolkits import mplot3d

Now let?s see how to make an empty mesh for our first 3D graph

code ?

from mpl_toolkits import mplot3d

import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import axes3d

fig = plt.figure()ax = plt.axes(projection=?3d?)


output ?

empty meshempty mesh

Now let?s add a line on our empty mesh ( on 3 axis)

code ?

mpl.rcParams[?legend.fontsize?] = 10fig = plt.figure()ax = fig.gca(projection=?3d?)theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)z = np.linspace(-2, 2, 100)r = z**2 + 1x = r * np.sin(theta)y = r * np.cos(theta)ax.plot(x, y, z, label=?parametric curve?)ax.legend()plt.show()

output ?

Image for postimage-A

The following image-B combines 2 plots, one with a line that goes through every point of the data, and other that draws a point on each of the particular 1000 values on this example.

(data on line is randomly generated using random function)

code ?

ax = plt.axes(projection=?3d?)# Data for a three-dimensional linezline = np.linspace(0, 15, 1000)xline = np.sin(zline)yline = np.cos(zline)ax.plot3D(xline, yline, zline, ?gray?)# Data for three-dimensional scattered pointszdata = 15 * np.random.random(100)xdata = np.sin(zdata) + 0.1 * np.random.randn(100)ydata = np.cos(zdata) + 0.1 * np.random.randn(100)ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap=?Greens?);

Output ?

Image for postImage-B


No Responses

Write a response