'Smooth surface Plot with Pyplot

My question is almost similar to this on: smoothing surface plot from matrix

only that my toolset is matplotlib and numpy (so far).

I have sucessfully generated a X, Y and Z-grid to plot with

fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='summer', rstride=1, cstride=1, alpa=None)

However, as the values are quite jumpy, it looks terribly. Exampleplot - terribly edgy, ugly... not usable and stuff

I'd like to smoothen things up, make at least the vertices connected, or look like that.

My data is generated like that: I have a function

svOfMatrix(x, y)

which produces a matrix in dependence on x, calculates its y-th power, selects a subset of columns and rows, and calculates the maximum singular value. So, Z[x,y] is svOfMatrix(x, y)

As this calculation is quite expensive, I don't want to make the steps for x too small, and Y is bound to be integer
Further, even for very small steps, there might be quite some changes, I don't want see. So I'd like to interpolate it somehow. I found http://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/interpolate.html but I don't get it to work.



Solution 1:[1]

Simply put the data_frame into this function. You'll get a proper smoothen surface plot. Incase you face any error, just choose only those features from data_frame which are numerical.

'data_frame = data_frame.select_dtypes(include='number')'

    from scipy import interpolate
    from mpl_toolkits.mplot3d import axes3d, Axes3D

    def surface(data_frame, title=None, title_x=0.5, title_y=0.9):

        X, Y = np.mgrid[-10:10:complex(0,data_frame.shape[0]), 
    -10:10:complex(0,data_frame.shape[1])]
        Z = data_frame.values

        xnew, ynew = np.mgrid[-1:1:80j, -1:1:80j]
        tck = interpolate.bisplrep(X, Y, Z, s=0)
        znew = interpolate.bisplev(xnew[:,0], ynew[0,:], tck)

        fig = go.Figure(data=[go.Surface(z=znew)])
        fig.update_layout(template='plotly_dark', 
                          width=800, 
                          height=800,
                          title = title,
                          title_x = title_x, 
                          title_y = title_y
                         )
        return fig

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 ASAD ASHRAF KAREL