我如何将熊猫多索引数据框绘制为3D

Mar*_*s W 3 python 3d matplotlib pandas seaborn

我有一个df像这样分组的数据框:

Year    Product Sales
2010        A   111
            B   20
            C   150
2011        A   10
            B   28
            C   190
            …   …
Run Code Online (Sandbox Code Playgroud)

我想将此绘制matplotlib为3d图表,其中Year以x为轴,Salesy轴Product为z轴。 在此处输入图片说明

我一直在尝试以下方法:

from mpl_toolkits.mplot3d import axes3d
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = dfgrouped['Year']
Y = dfgrouped['Sales']
Z = dfgrouped['Product']
ax.bar(X, Y, Z, color=cs, alpha=0.8)
Run Code Online (Sandbox Code Playgroud)

不幸的是我越来越

“ ValueError:大小不兼容:参数'height'必须为长度7或标量”

Nic*_*eli 5

您可以Pandas如下所示绘制3D条形图:

设定:

arrays = [[2010, 2010, 2010, 2011, 2011, 2011],['A', 'B', 'C', 'A', 'B', 'C']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['Year', 'Product'])         

df = pd.DataFrame({'Sales': [111, 20, 150, 10, 28, 190]}, index=index)
print (df)

              Sales
Year Product       
2010 A          111
     B           20
     C          150
2011 A           10
     B           28
     C          190
Run Code Online (Sandbox Code Playgroud)

数据整理:

import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

# Set plotting style
plt.style.use('seaborn-white')
Run Code Online (Sandbox Code Playgroud)

对出现在“销售”列中的相似条目(get_group)进行分组,并对其进行迭代,然后将其附加到list。使用3D图np.hstackz尺寸将其水平堆叠。

L = []
for i, group in df.groupby(level=1)['Sales']:
    L.append(group.values)
z = np.hstack(L).ravel()
Run Code Online (Sandbox Code Playgroud)

让x和y维度上的标签都采用Multi-Index Dataframe各个级别的唯一值。然后,x和y尺寸取这些值的范围。

xlabels = df.index.get_level_values('Year').unique()
ylabels = df.index.get_level_values('Product').unique()
x = np.arange(xlabels.shape[0])
y = np.arange(ylabels.shape[0])
Run Code Online (Sandbox Code Playgroud)

使用以下命令从坐标向量返回坐标矩阵 np.meshgrid

x_M, y_M = np.meshgrid(x, y, copy=False)
Run Code Online (Sandbox Code Playgroud)

3-D绘图:

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

# Making the intervals in the axes match with their respective entries
ax.w_xaxis.set_ticks(x + 0.5/2.)
ax.w_yaxis.set_ticks(y + 0.5/2.)

# Renaming the ticks as they were before
ax.w_xaxis.set_ticklabels(xlabels)
ax.w_yaxis.set_ticklabels(ylabels)

# Labeling the 3 dimensions
ax.set_xlabel('Year')
ax.set_ylabel('Product')
ax.set_zlabel('Sales')

# Choosing the range of values to be extended in the set colormap
values = np.linspace(0.2, 1., x_M.ravel().shape[0])

# Selecting an appropriate colormap
colors = plt.cm.Spectral(values)
ax.bar3d(x_M.ravel(), y_M.ravel(), z*0, dx=0.5, dy=0.5, dz=z, color=colors)
plt.show()
Run Code Online (Sandbox Code Playgroud)

图片


注意:

对于不平衡的groupby对象,您仍然可以通过unstacking 填充Nans0来实现,然后stacking返回如下:

df = df_multi_index.unstack().fillna(0).stack()
Run Code Online (Sandbox Code Playgroud)

df_multi_index.unstack您原始的多索引数据框在哪里。

对于添加到多索引数据框中的新值,将获得以下图表:

图片2