I’m facing a problem with making a 3D plot. I want to build a 3D surface plot like below from three columns of data. Expected graphic case
I have implemented a few currently, as shown below. Current picture case But I still don’t know how to make it “grid” like the first picture? Does anyone know how to achieve this? Part of the code and full data are as follows.
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import os
import warnings
from mpl_toolkits.mplot3d import Axes3D
warnings.filterwarnings('ignore')
os.chdir(r"E:SoftwareFilestataFile")
matplotlib.use('TkAgg')
plt.figure(figsize=(10,6))
data = pd.read_stata(r"E:SoftwareFilestataFiledemo.dta")
ax = plt.axes(projection="3d")
ax.plot_trisurf(data["age"], data["weight"], data["pr_highbp"],
cmap=plt.cm.Spectral_r)
ax.set_xticks(np.arange(20, 90, step=10))
ax.set_yticks(np.arange(40, 200, step=40))
ax.set_zticks(np.arange( 0, 1.2, step=0.2))
ax.set_title("Probability of Hypertension by Age and Weight")
ax.set_xlabel("Age (years)")
ax.set_ylabel("Weight (kg")
ax.zaxis.set_rotate_label(False)
ax.set_zlabel("Probability of Hypertension", rotation=90)
ax.view_init(elev=30, azim=240)
plt.savefig("demo.png", dpi=1200)
Download all data Sincerely appreciate your help
Advertisement
Answer
Remove the colormap and opacity in the trisurf command like so:
ax.plot_trisurf( data["age"], data["weight"], data["pr_highbp"], color=None, linewidth=1, antialiased=True, edgecolor="Black", alpha=0, )
That should result in:
You could also take a look at plot_wireframe(). For that I think you have to start with
x = data["age"].to_list() y = data["weight"].to_list() X, Y = np.meshgrid(x, y)
But I’m not sure how to create the z coordinate. It seems you may need interpolation from what I read.
