Reputation: 651
Alright, I'm trying to plot a matplotlib 3d surface graph.
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import itertools as it
import numpy as np
plt.clf()
fig = plt.figure(figsize=(6.27, 9.69))
ax = Axes3D(fig)
x = list(range(1,101,11))
y = list(range(1,101,11))
df = pd.DataFrame(columns=y, index=x)
iterator = it.product(x,y)
for i in iterator:
number = np.random.rand()
df.loc[i[0],i[1]] = number
surf = ax.plot_surface(df.index,
df.columns,
df,
cmap='viridis_r',
linewidth=0.5,
alpha = 0.5,
edgecolor = 'k')
ax.set_xlim3d(0,101)
ax.set_ylim3d(0,101)
ax.invert_yaxis()
cb = fig.colorbar(surf, shrink=0.8 , alpha = 0.5)
cb.solids.set_edgecolor("face")
plt.show()
My code works (after a fashion) but all my results only appear on a straight line where x=y
i.e. a 2d graph.
I had thought it might be something to do with my use of itertools (the code not cycling through all the iterations) but the dataframe seems fine.
Can anybody tell me what I'm doing wrong?
Upvotes: 0
Views: 319
Reputation: 249
I checked, and you do need to compute a grid before plotting. You can just add something like :
...
for i in iterator:
number = np.random.rand()
df.loc[i[0],i[1]] = number
xv, yv = np.meshgrid(df.index, df.columns)
surf = ax.plot_surface(xv,
yv,
df,
cmap='viridis_r',
linewidth=0.5,
alpha = 0.5,
edgecolor = 'k')
...
I don't really know if this is the expected result, but you obtain a real surface !
meshgrid
just creates matrices which correspond to different permutations of values from x and y, to allow you to have different x for one y and vice versa.
Upvotes: 1