DataFrame:如何使用索引和列作为 x 和 y,数据作为 z 来绘制 3D 图形?
DataFrame: how to draw a 3D graph using Index and Columns as x and y, and data as z?
我的DataFrame行索引和列索引存储x
和y
值,而数据值是z
值,即f(x, y)
.
举个例子:
import pandas as pd
df = pd.DataFrame([[150, 120, 170], [190, 160, 130]],
index=[2, 4], columns=[10, 30, 70])
print(df)
# 10 30 70
# 2 150 120 170
# 4 190 160 130
那么f(4, 30)
就是160
。
我想绘制函数 f
的 3D 图。我真的不介意它看起来像 3D 直方图还是曲面图 - 两个答案都将不胜感激。
您需要创建一个 meshgrid
from your row and col indices and then you can use plot_surface
:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame([[150, 120, 170], [190, 160, 130]],
index=[2, 4], columns=[10, 30, 70])
x,y = np.meshgrid(df.columns, df.index)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(x, y, df)
我的DataFrame行索引和列索引存储x
和y
值,而数据值是z
值,即f(x, y)
.
举个例子:
import pandas as pd
df = pd.DataFrame([[150, 120, 170], [190, 160, 130]],
index=[2, 4], columns=[10, 30, 70])
print(df)
# 10 30 70
# 2 150 120 170
# 4 190 160 130
那么f(4, 30)
就是160
。
我想绘制函数 f
的 3D 图。我真的不介意它看起来像 3D 直方图还是曲面图 - 两个答案都将不胜感激。
您需要创建一个 meshgrid
from your row and col indices and then you can use plot_surface
:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame([[150, 120, 170], [190, 160, 130]],
index=[2, 4], columns=[10, 30, 70])
x,y = np.meshgrid(df.columns, df.index)
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(x, y, df)