Home > Enterprise >  How to do a 3D plot in matplotlib where two functions are evaluated with only one variable?
How to do a 3D plot in matplotlib where two functions are evaluated with only one variable?

Time:11-06

All 3D plot examples I find are of the form X,Y = data and f(X,Y) is the plotted function. What I need is a 3D plot where X contains data points while Y = f(X) and Z = g(X) are displayed on the respective axes. Is there a way to do so?

CodePudding user response:

IIUC, you can set x_points on DataFarme then apply function_y and function_z on DataFrame then plot points like below:

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

def create_Y(x):
    return x**2   2*x - 10

def create_Z(x):
    return np.sin(x)


df = pd.DataFrame({'X': np.linspace(0.0, 3.0, num=500)})
df['Y'] = df['X'].apply(create_Y)
df['Z'] = df['X'].apply(create_Z)

fig = plt.figure(figsize=(12,7))
ax = fig.add_subplot(projection = '3d')
ax.plot(xs = df['X'], ys = df['Y'],zs = df['Z'])
plt.show()

Output:

enter image description here

  • Related