Python的3D绘图多dataframes(Python 3D plot for multiple

2019-09-28 05:53发布

假设我有三个Python的熊猫DataFrames:

df_sale = pd.DataFrame([[20,30,10], [30,20,20], [20,40,40]], columns=list("ABC"))

    A   B   C
0   20  30  10
1   30  20  20
2   20  40  40

df_people = pd.DataFrame([[2,3,1], [3,2,2], [2,4,4]], columns=list("ABC"))

    A   B   C
0   2   3   1
1   3   2   2
2   2   4   4

df_department = pd.DataFrame([[1,2,1], [1,1,2], [2,1,1]], columns=list("ABC"))

    A   B   C
0   1   2   1
1   1   1   2
2   2   1   1

如何绘制在同一个地方所有这些3个dataframes三维条形图?

我想X轴为['A', 'B', 'C'] ,Y轴是dataframes的名称['df_sale', 'df_people', 'df_department'] ,和Z轴,以显示数字。

Answer 1:

你可以使用matplotlib的3D酒吧 。

import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

columns = ['A', 'B', 'C']
df_names = ['sale', 'people', 'department']
df = [pd.DataFrame([[20,30,10], [30,20,20], [20,40,40]], columns=columns), pd.DataFrame([[2,3,1], [3,2,2], [2,4,4]], columns=columns), pd.DataFrame([[1,2,1], [1,1,2], [2,1,1]], columns=columns)]

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

#make sure x and y axis get the right tick labels
plt.xticks([i for i in range(len(columns))], columns)
plt.yticks([i for i in range(len(df_names))], df_names)

#define a list for x positions
xs = list()
for i in range(len(df)):
    for j in range(len(columns)):
         xs.append(i + j * 0.1)

for c1, c in enumerate(['r', 'g', 'b']):
    ys = list()
    for i in range(len(columns)):
        ys.extend(df[c1].ix[:,i:i+1].unstack().tolist())
    cs = [c] * len(xs)    
    ax.bar(xs, ys, zs=c1, zdir='y', color=cs, alpha=0.5, width=0.1)

plt.show()


Multicolors和传说

import matplotlib
colors = ['r', 'g', 'b', 'c', 'm', 'y', '#eeefff', '#feefff', '#aeefff']
for c1 in range(3):
    ys = list()
    for i in range(len(columns)):
        ys.extend(df[c1].ix[:,i:i+1].unstack().tolist())
    ax.bar(xs, ys, zs=c1, zdir='y', color=colors, alpha=0.5, width=0.1)

legend = list()
for i, c in enumerate(colors):
    legend.append(matplotlib.patches.Patch(color=c, label='value {0} of column {1}'.format(i % 3, columns[i // 3])))
plt.legend(handles=legend, loc=4, bbox_to_anchor=(.9, 0), mode="expand")
plt.show()



文章来源: Python 3D plot for multiple dataframes