Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Is there a way to plot a "partial" surface plot with Matplotlib?

I wanted to plot a "partial" surface plot like the following one with Matplotlib example

Note that it's not a complete meshgrid on X-Y plane but missing a corner from top view. The following is the code I tried but didn't work.

import numpy as np
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D

X = np.array([[0,1],
              [0,1,2],
              [0,1,2,3],
             ])
Y = np.array([[0,0],
              [1,1,1],
              [2,2,2,2],
             ])
Z = np.array([[0.5, 0.6],
              [0.7, 0.8, 0.9],
              [1.0, 1.1, 1.2, 1.3],
             ])
fig = pyplot.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X,Y,Z)

The error being:

ValueError: setting an array element with a sequence.

Any pointer would be appreciated! Thanks!

like image 805
Shawn Avatar asked Mar 19 '16 20:03

Shawn


People also ask

How do I shade part of a plot in matplotlib?

Plot x and y data points, with color=red and linewidth=2. To shade an area parallel to X-axis, initialize two variables, y1 and y2. To add horizontal span across the axes, use axhspan() method with y1, y2, green as shade color,and alpha for transprency of the shade. To display the figure, use show() method.

Is there anything better than matplotlib?

Plotly has several advantages over matplotlib. One of the main advantages is that only a few lines of codes are necessary to create aesthetically pleasing, interactive plots. The interactivity also offers a number of advantages over static matplotlib plots: Saves time when initially exploring your dataset.


1 Answers

You can do this easily by using np.nan values for Z in the regions you don't want to plot. Here's a modified version of this example but with the cut, as show below:

enter image description here

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(.5*R)

Z[X+Y>4.] = np.nan  # the diagonal slice

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False, vmin=-1, vmax=1)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

Note here also that I had to use vmin and vmax keywords in the plot command or the color scaling would be thrown by the nans.

like image 63
tom10 Avatar answered Sep 18 '22 10:09

tom10