2017-06-28 67 views
1

我很努力地左右對齊文本,而不會浪費列中的空間。同樣的山坳寬度被用於中心/左/右:表中的Matplotlib文本對齊方式

  1. Center aligned:正確居中,確定
  2. Left aligned:左側
  3. 浪費的空間即使省略colWidths如表參數,並與玩弄我最喜歡的解決方案the_table._autoColumns = range(-1,len(colLabels))不會改善這種情況

我在做什麼錯?這是matplotlib中的錯誤嗎?

最好的問候, 勒

import pandas as pd 
import matplotlib.pyplot as plt 

size_x, size_y = 12, 4 
fig = plt.figure (figsize=(size_x, size_y)) 
ax = fig.add_subplot(111) 

col_ID = pd.Series ([ "R001", "R002", "R003", "R005", "R006", "R007" ]) 
col_Title = pd.Series ([ 50*"*", 10*"-", 70*"x", "R005", "R006", "R007" ]) 
col_x  = pd.Series ([ 3,  1,  3,  4,  2,  3 ]) 
col_y  = pd.Series ([ 4,  2,  3,  2,  4,  3 ]) 

legend_df = pd.DataFrame ({ "ID" : col_ID, 
          "Title" : col_Title, 
          "X-Pos" : col_x, 
          "Y-Pos" : col_y, 
          "Value" : col_x * col_y }) 
rowLabels = legend_df.index 
colLabels = legend_df.columns 
cellText = legend_df.values 

# Center-Aligned text looks ok 
the_table = plt.table (cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, loc='upper center', cellLoc="center", colWidths=[0.05, 0.52, 0.05, 0.05, 0.05, 0.05]) 

# Bogus: Same colWidths, but left OR right aligned -> unwanted space in title column 
# the_table = ax.table (cellText=cellText, rowLabels=rowLabels, colLabels=colLabels, loc='upper center', cellLoc="left", colWidths=[0.05, 0.52, 0.05, 0.05, 0.05, 0.05]) 

the_table.auto_set_font_size(False) 
the_table.set_fontsize (8) 

# Set col width automatically 
# the_table._autoColumns = range (-1,len (colLabels)) 

ax.xaxis.set_visible (False)           # Grafik-Achsen ausschalten, wir wollen nur Plot 
ax.yaxis.set_visible (False) 
# the_table.scale(2, 2) 

plt.show() 

回答

1

每默認情況下,電池有10%的填充雙方,這是非常有用的讓文字開始旁邊的表格單元格邊框一點。對於非常大的電池,10%太多,導致不希望的大空間。

enter image description here

爲了克服這一點,就需要在問題設置填充的列到一個較低的值,爲所有其他列的10%實際上是desireable。沒有內置選項來設置填充,但可以通過循環遍歷列的單元格並更改相應的屬性來操作它。

def set_pad_for_column(col, pad=0.1): 
    cells = [key for key in the_table._cells if key[1] == col] 
    for cell in cells: 
     the_table._cells[cell].PAD = pad 

set_pad_for_column(col=1, pad=0.01) 

這將僅爲第二列(col=1)生成1%的填充。

enter image description here

+0

感謝您的快速響應。填充值取決於字體大小而不是列寬是不是更好? –

+0

在matplotlib中編寫表類的方式,沒有辦法將填充更改爲字體大小相關 - 除了子類化表類和單元類並重新實現相應的方法。你是否問我對這個設計選擇的看法? – ImportanceOfBeingErnest

+0

也許值得在matplotlib中打開一個bug?從我的角度來看,存在解決方法(您的解決方案),但理智的默認值/算法應該存在,以便用戶不必調整實現內部 - 您的意見是什麼? –