gpt4 book ai didi

python - 如何使用带有 matplotlib 的 pandas 来创建 3D 图

转载 作者:行者123 更新时间:2023-12-04 03:58:30 25 4
gpt4 key购买 nike

在 matplot 库上以 3D 形式呈现数据所需的 pandas 转换让我有些吃力。我拥有的数据通常是数字列(通常是时间和一些值)。因此,让我们创建一些测试数据来说明。

import pandas as pd

pattern = ("....1...."
"....1...."
"..11111.."
".1133311."
"111393111"
".1133311."
"..11111.."
"....1...."
"....1....")

# create the data and coords
Zdata = list(map(lambda d:0 if d == '.' else int(d), pattern))
Zinverse = list(map(lambda d:1 if d == '.' else -int(d), pattern))
Xdata = [x for y in range(1,10) for x in range(1,10)]
Ydata = [y for y in range(1,10) for x in range(1,10)]
# pivot the data into columns
data = [d for d in zip(Xdata,Ydata,Zdata,Zinverse)]

# create the data frame
df = pd.DataFrame(data, columns=['X','Y','Z',"Zi"], index=zip(Xdata,Ydata))
df.head(5)

enter image description here

Edit: This block of data is demo data that would normally come from a query on adatabase that may need more cleaning and transforms before plotting. In this case data is already aligned and there are no problems aside having one more column we don't need (Zi).

所以pattern中的数字被转移到df的Z列中的高度数据('Zi'是反图像)并以此作为数据框I一直在努力想出这种枢轴方法,它是 3 个独立的操作。我想知道是否可以做得更好。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Xs = df.pivot(index='X', columns='Y', values='X').values
Ys = df.pivot(index='X', columns='Y', values='Y').values
Zs = df.pivot(index='X', columns='Y', values='Z').values

ax.plot_surface(Xs,Ys,Zs, cmap=cm.RdYlGn)

plt.show()

enter image description here

虽然我有一些工作,但我觉得一定有比我正在做的更好的方法。在大数据集上,我认为做 3 个枢轴点是一种昂贵的绘图方式。有没有更有效的方法来转换这些数据?

最佳答案

我想您可以通过不使用 pandas(但仅使用 numpy 数组)并使用 numpy 提供的一些便利函数(例如 linespace)来避免数据准备过程中的一些步骤。和 meshgrid .

我为此重写了您的代码,试图保持相同的逻辑和相同的变量名称:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

pattern = ("....1...."
"....1...."
"..11111.."
".1133311."
"111393111"
".1133311."
"..11111.."
"....1...."
"....1....")


# Extract the value according to your logic
Zdata = list(map(lambda d:0 if d == '.' else int(d), pattern))

# Assuming the pattern is always a square
size = int(len(Zdata) ** 0.5)

# Create a mesh grid for plotting the surface
Xdata = np.linspace(1, size, size)
Ydata = np.linspace(1, size, size)
Xs, Ys = np.meshgrid(Xdata, Ydata)

# Convert the Zdata to a numpy array with the appropriate shape
Zs = np.array(Zdata).reshape((size, size))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot the surface
ax.plot_surface(Xs, Ys, Zs, cmap=cm.RdYlGn)
plt.show()

关于python - 如何使用带有 matplotlib 的 pandas 来创建 3D 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63474824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com