2017-06-28 150 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?从我的角度来看,存在解决方法(您的解决方案),但理智的默认值/算法应该存在,以便用户不必调整实现内部 - 您的意见是什么? –