'Surface plot in matplotlib

I am having trouble performing surface plot operation in Python, using the matplotlib library. Below is my code snippet

However, I get an error stating that 'Figure' object has no property 'projection'. Without using the projection property, I get an error that ax1 has no function called plot_surface

How can I resolve this error ?

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import pyautogui
from scipy import stats

x = pyautogui.size()
width = x.width
height = x.height

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)
data = 2*(np.sin(X) + np.sin(3*Y))

fig, (ax, ax1) = plt.subplots(2, 1, projection='3d')
fig.set_figheight(height/100)
fig.set_figwidth(width/100)
fig.set_dpi(100)
im = ax.pcolormesh(X, Y, data, cmap='viridis')
cbar = plt.colorbar(im, ax=ax)
cbar.set_label('ColorbarLabel', size=15)
surf = ax1.plot_surface(X, Y, data, cmap='virdis')
cbar1 = plt.colorbar(surf, ax=ax1)
cbar1.set_label('Colorbar2', size=15)
ax.set_xlabel('x_label')
ax.set_ylabel('y_label')
ax.set_title('Title')


Solution 1:[1]

Seems like I can solve the problem by adding subplots seperately to the figure object. Is this the most efficient and correct way to achieve my goals ?

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import pyautogui
from scipy import stats

x = pyautogui.size()
width = x.width
height = x.height

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)
data = 2*(np.sin(X) + np.sin(3*Y))

fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
ax1 = fig.add_subplot(2, 1, 2, projection='3d')
fig.set_figheight(height/100)
fig.set_figwidth(width/100)
fig.set_dpi(100)
im = ax.pcolormesh(X, Y, data, cmap='viridis')
cbar = plt.colorbar(im, ax=ax)
cbar.set_ticks([0.2, 0.4, 0.6, 0.8])
cbar.set_ticklabels(["A", "B", "C", "D"])
cbar.set_label('ColorbarLabel', size=15)
surf = ax1.plot_surface(X, Y, data, cmap='jet')
cbar1 = plt.colorbar(surf, ax=ax1)
cbar.set_label('Colorbar2', size=15)
ax.set_xlabel('x_label')
ax.set_ylabel('y_label')
ax.set_title('Title')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Masoom Kumar