2015-12-02 41 views
2

是否可以使用matplotlib以pandas顯示錶格的方式繪製具有多索引的表格?我在網上找到的最多的是這個open git issue from 2012用多索引繪製matplotlib表格

考慮下面的示例數據幀:

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], 
      ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] 

tuples = list(zip(*arrays)) 
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) 
df = pd.DataFrame(np.random.randn(8, 4), index=arrays) 

它打印如下: enter image description here

但是當我嘗試創建一個表出來的這種使用下面的例子:

fig=plt.figure(figsize=(9.5, 11)) 
plt.gca().axis('off') 
matplotlib_tab = pd.tools.plotting.table(plt.gca(), 
             df, 
             loc='upper center', 
             colWidths=[0.25]*len(df.columns))  

table_props=matplotlib_tab.properties() 
table_cells=table_props['child_artists'] 
for cell in table_cells: 
    cell.set_height(0.024) 
    cell.set_fontsize(12) 

fig.text(4.25/8.5, 10.5/11., 'plot', ha='center', fontsize=12) 
plt.plot() 

我得到了如下圖表(注意左邊的索引不一樣):

enter image description here

回答

1

一個不完整的答案 Matplotlib.table.tablepandas.tools.plotting.table遍歷數據幀的多指標,如表中所示,返回的元組稱爲阿位。我檢查了兩個函數的源代碼,似乎它目前不支持任何形式的多行或多列表。

如果該表是獨立表,那麼爲什麼不使用支持多索引的df.to_html()

<table border="1" class="dataframe"> 
 
    <thead> 
 
    <tr style="text-align: right;"> 
 
     <th></th> 
 
     <th></th> 
 
     <th>0</th> 
 
     <th>1</th> 
 
     <th>2</th> 
 
     <th>3</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <th rowspan="2" valign="top">bar</th> 
 
     <th>one</th> 
 
     <td>0.578703</td> 
 
     <td>1.499785</td> 
 
     <td>-1.144682</td> 
 
     <td>0.957464</td> 
 
    </tr> 
 
    <tr> 
 
     <th>two</th> 
 
     <td>1.116768</td> 
 
     <td>0.291652</td> 
 
     <td>-0.095254</td> 
 
     <td>0.131653</td> 
 
    </tr> 
 
    <tr> 
 
     <th rowspan="2" valign="top">baz</th> 
 
     <th>one</th> 
 
     <td>-1.119140</td> 
 
     <td>0.245226</td> 
 
     <td>0.453203</td> 
 
     <td>-1.827160</td> 
 
    </tr> 
 
    <tr> 
 
     <th>two</th> 
 
     <td>0.442228</td> 
 
     <td>0.160754</td> 
 
     <td>1.199452</td> 
 
     <td>0.767720</td> 
 
    </tr> 
 
    <tr> 
 
     <th rowspan="2" valign="top">foo</th> 
 
     <th>one</th> 
 
     <td>0.621110</td> 
 
     <td>0.334196</td> 
 
     <td>1.854065</td> 
 
     <td>0.505222</td> 
 
    </tr> 
 
    <tr> 
 
     <th>two</th> 
 
     <td>-0.269477</td> 
 
     <td>1.294712</td> 
 
     <td>0.421114</td> 
 
     <td>0.018712</td> 
 
    </tr> 
 
    <tr> 
 
     <th rowspan="2" valign="top">qux</th> 
 
     <th>one</th> 
 
     <td>-1.736962</td> 
 
     <td>-2.627593</td> 
 
     <td>-0.843875</td> 
 
     <td>-2.108532</td> 
 
    </tr> 
 
    <tr> 
 
     <th>two</th> 
 
     <td>-1.200400</td> 
 
     <td>-0.319079</td> 
 
     <td>0.529251</td> 
 
     <td>-1.928900</td> 
 
    </tr> 
 
    </tbody> 
 
</table>