close

How to surface plot/3d plot from dataframe?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to surface plot/3d plot from dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to surface plot/3d plot from dataframe?

  1. How to surface plot/3d plot from dataframe?

    You can transform the DataFrame with numpy in a formulaic way to render it as a surface.

  2. surface plot/3d plot from dataframe

    You can transform the DataFrame with numpy in a formulaic way to render it as a surface.

Method 1

You can transform the DataFrame with numpy in a formulaic way to render it as a surface.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


def plottable_3d_info(df: pd.DataFrame):
    """
    Transform Pandas data into a format that's compatible with
    Matplotlib's surface and wireframe plotting.
    """
    index = df.index
    columns = df.columns

    x, y = np.meshgrid(np.arange(len(columns)), np.arange(len(index)))
    z = np.array([[df[c][i] for c in columns] for i in index])
    
    xticks = dict(ticks=np.arange(len(columns)), labels=columns)
    yticks = dict(ticks=np.arange(len(index)), labels=index)
    
    return x, y, z, xticks, yticks


### Compose your data.
the_data = pd.DataFrame(
    data=[
        [11.0, 1.20, 1.20, 0.90],
        [11.43, 1.31, 1.32, 0.95],
        [12.01, 1.45, 1.47, 1.11],
    ],
    index=['triangle', 'square', 'hexagon'],
    columns=['sodium', 'nylon 11', 'nylon 12', 'abs'],
)

### Transform to Matplotlib friendly format.
x, y, z, xticks, yticks = plottable_3d_info(the_data)

### Set up axes and put data on the surface.
axes = plt.figure().gca(projection='3d')
axes.plot_surface(x, y, z)

### Customize labels and ticks (only really necessary with
### non-numeric axes).
axes.set_xlabel('material')
axes.set_ylabel('shape')
axes.set_zlabel('USD per item')
axes.set_zlim3d(bottom=0)
plt.xticks(**xticks)
plt.yticks(**yticks)

plt.show()

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read