如何从 pandas 数据框中的三列创建 2D 绘图

问题描述 投票:0回答:1

我想为一些标量数据 z 制作一个简单的二维图(如 imshow 或轮廓),该数据取决于两个标量输入变量 x 和 y (因此 z = f(x,y))。

但是,我不知道依赖项的分析功能,我宁愿将所有数据放在 pandas 数据框中的三列 x,y 和 z 中,例如:

import pandas as pd

d = {'x': [1, 1, 1, 2, 2, 2], 
     'y': [1, 2, 3, 1, 2, 3], 
     'z': [30, 31, 33, 10, 8, 6]}
df = pd.DataFrame(data=d)

这应该相当容易,但是我还没有找到解决方案。非常感谢帮助! 谢谢

我尝试使用网格网格和轮廓,但我不知道如何相应地重塑我的 z 数据。

python pandas plot contour
1个回答
0
投票

您可以使用 Python 可视化库 matplotlib 绘制数据的 2D 绘图。给定您的数据结构,可视化数据的最简单方法之一是创建散点图,但是,要创建 imshow 或等值线图,数据需要采用网格/矩阵格式。以下是如何转换数据并创建 imshow 图和等高线图:

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

# Your data
d = {'x': [1, 1, 1, 2, 2, 2], 
     'y': [1, 2, 3, 1, 2, 3], 
     'z': [30, 31, 33, 10, 8, 6]}
df = pd.DataFrame(data=d)

# Convert the x, y, z data to grid format
x = df['x'].values
y = df['y'].values
z = df['z'].values
x_unique = np.unique(x)
y_unique = np.unique(y)
z_matrix = z.reshape(len(x_unique), len(y_unique))

# Create a 2D imshow plot
plt.figure()
plt.imshow(z_matrix, origin='lower', aspect='auto', extent=[x_unique.min(), x_unique.max(), y_unique.min(), y_unique.max()])
plt.colorbar(label='z')
plt.xlabel('x')
plt.ylabel('y')
plt.title('imshow plot')
plt.show()

# Create a contour plot
plt.figure()
X, Y = np.meshgrid(x_unique, y_unique)
plt.contourf(X, Y, z_matrix, levels=50)
plt.colorbar(label='z')
plt.xlabel('x')
plt.ylabel('y')
plt.title('contour plot')
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.