2017-01-04 11 views
1

は、私は3つのPythonのパンダのデータフレームを持っていると仮定すると:のPythonの3Dプロット

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つのデータフレームと3D棒グラフをプロットしますか?

X軸を['A', 'B', 'C']、Y軸をデータフレーム名['df_sale', 'df_people', 'df_department']、Z軸を数値として表示します。

答えて

2

matplotlib's 3D barsを使用できます。

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() 

enter image description here


多色とlegend

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() 

enter image description here

+0

こんにちはマックス、あなたの答えに感謝して、これは私の質問のほとんどを解決します。しかし、インデックス名が数字[0,1,2,3 ...]でない場合はどうなるのだろうか。 df [c1] .ix [:、i:i + 1]この部分は数字のみで動作します。また、異なる色で3つのバーを一緒に色付けする方法はありますか?例えばバーは「A」、「Sales」の下にあります。赤、緑、青の色にしたい場合はどうでしょうか?彼らは時間を表すかもしれないので(1月、2月、3月)。そして、同じ色が人や部門に適用されます。最後に、色の伝説を追加します。これは実行可能ですか?ありがとう! – thatMeow

+0

pandas ixのドキュメント: "主にラベル位置ベースのインデクサーで、整数位置のフォールバックを持つ"、つまりあなたは良いです。 –

+0

@AlexMeow:マルチカラーオプションと凡例に関する最新の回答をご覧ください –

関連する問題