简体   繁体   English

来自2D熊猫数据帧的Matplotlib 3D表面图

[英]Matplotlib 3D surface plot from 2D pandas dataframe

I have a pandas dataframe containing four columns of measurement data. 我有一个包含四列测量数据的pandas数据帧。 I'd like to create a 3D surface plot with the row index as X, the column index as Y, and the data as Z. (The data in each column is a series of discrete measurements output from a test that steps through all values of X for each category Y) 我想创建一个三维曲面图,行索引为X,列索引为Y,数据为Z.(每列中的数据是一系列离散测量输出,来自测试,逐步执行所有值每个类别X的X)

import pandas as pd
import numpy as np


df = pd.DataFrame(np.random.randn(5, 4), columns=['A', 'B', 'C', 'D'])
print(df)

   A         B         C         D
0  0.791692 -0.945571  0.183304  2.039369
1 -0.474666  1.117902 -0.483240  0.137620
2  1.448765  0.228217  0.294523  0.728543
3 -0.196164  0.898117 -1.770550  1.259608
4  0.646730 -0.366295 -0.893671 -0.745815

I tried converting the df into a numpy grid using np.meshgrid as below but not sure I really understand what is required, or if I can use the df indices in this way. 我尝试使用np.meshgrid将df转换为numpy网格,如下所示,但不确定我是否真正了解所需内容,或者是否可以这样使用df索引。

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

x = df.columns
y = df.index
X,Y = np.meshgrid(x,y)
Z = df
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)

I've read through the matplotlib 3D tutorial and related answers here, but am still stuck. 我在这里阅读了matplotlib 3D教程及相关答案,但仍然卡住了。 Would be very grateful if someone could point me in the right direction please. 如果有人能指出我正确的方向,请将非常感激。

The general strategy you pursue is fine. 你追求的一般策略很好。 The only error you have is that you create a meshgrid from a list of strings. 您唯一的错误是您从字符串列表创建meshgrid。 Of course maplotlib cannot plot strings. 当然maplotlib不能绘制字符串。

You can therfore create an array of the same length as the number of columns in your dataframe and plug that into the meshgrid . 因此,您可以创建一个与数据meshgrid列数相同长度的数组,并将其插入到meshgrid

x = np.arange(len(df.columns))

just take of the columns names (['A', 'B', 'C', 'D']) and it should work. 只需要列名称(['A','B','C','D']),它应该工作。

you can later change the ticks of the axis for ['A', 'B', 'C', 'D']. 您可以稍后更改['A','B','C','D']的轴的刻度。

import pandas as pd
import numpy as np


df = pd.DataFrame(np.random.randn(5, 4))

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

x = df.columns
y = df.index
X,Y = np.meshgrid(x,y)
Z = df
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM