My DataFrame line index and column index store x
and y
values, while the data values are z
values, i.e. f(x, y)
.
Let’s take an example:
JavaScript
x
8
1
import pandas as pd
2
df = pd.DataFrame([[150, 120, 170], [190, 160, 130]],
3
index=[2, 4], columns=[10, 30, 70])
4
print(df)
5
# 10 30 70
6
# 2 150 120 170
7
# 4 190 160 130
8
then f(4, 30)
is 160
.
I would like to make a 3D plot of function f
. I don’t really mind if it looks like a 3D histogram or a surface plot – both answers would be appreciated.
Advertisement
Answer
You need to create a meshgrid
from your row and col indices and then you can use plot_surface
:
JavaScript
1
9
1
import pandas as pd
2
import numpy as np
3
import matplotlib.pyplot as plt
4
df = pd.DataFrame([[150, 120, 170], [190, 160, 130]],
5
index=[2, 4], columns=[10, 30, 70])
6
x,y = np.meshgrid(df.columns, df.index)
7
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
8
ax.plot_surface(x, y, df)
9