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.
JavaScript
x
35
35
1
import numpy as np
2
import pandas as pd
3
import matplotlib
4
import matplotlib.pyplot as plt
5
import os
6
import warnings
7
from mpl_toolkits.mplot3d import Axes3D
8
9
warnings.filterwarnings('ignore')
10
os.chdir(r"E:SoftwareFilestataFile")
11
matplotlib.use('TkAgg')
12
13
plt.figure(figsize=(10,6))
14
15
data = pd.read_stata(r"E:SoftwareFilestataFiledemo.dta")
16
17
ax = plt.axes(projection="3d")
18
19
ax.plot_trisurf(data["age"], data["weight"], data["pr_highbp"],
20
cmap=plt.cm.Spectral_r)
21
22
23
ax.set_xticks(np.arange(20, 90, step=10))
24
ax.set_yticks(np.arange(40, 200, step=40))
25
ax.set_zticks(np.arange( 0, 1.2, step=0.2))
26
27
ax.set_title("Probability of Hypertension by Age and Weight")
28
ax.set_xlabel("Age (years)")
29
ax.set_ylabel("Weight (kg")
30
ax.zaxis.set_rotate_label(False)
31
ax.set_zlabel("Probability of Hypertension", rotation=90)
32
33
ax.view_init(elev=30, azim=240)
34
plt.savefig("demo.png", dpi=1200)
35
Download all data Sincerely appreciate your help
Advertisement
Answer
Remove the colormap and opacity in the trisurf command like so:
JavaScript
1
11
11
1
ax.plot_trisurf(
2
data["age"],
3
data["weight"],
4
data["pr_highbp"],
5
color=None,
6
linewidth=1,
7
antialiased=True,
8
edgecolor="Black",
9
alpha=0,
10
)
11
That should result in:
You could also take a look at plot_wireframe()
. For that I think you have to start with
JavaScript
1
4
1
x = data["age"].to_list()
2
y = data["weight"].to_list()
3
X, Y = np.meshgrid(x, y)
4
But I’m not sure how to create the z coordinate. It seems you may need interpolation from what I read.