在挖掘Table类和Text类之后,我设法生成一个宽度和高度不相等的表,这取决于单元格内部文本的大小(我借用matplotlib示例):
"""
Demo of table function to display a table within a plot.
"""
import numpy as np
import matplotlib.pyplot as plt
#from matplotlib.backends.backend_pdf import PdfPages
data = [[ 66386, 174296, 75131, 577908, 32015],
[ 58230, 381139, 78045, 99308, 160454],
[ 89135, 80552, 152558, 497981, 603535],
[ 78415, 81858, 150656, 193263, 69638],
[ 139361, 331509, 343164, 781380, 52269]]
columns = ('Freeze', 'Tornados', 'Flood', 'Quake', 'Hail')
n_rows = len(data)
y_offset = np.array([0.0] * len(columns))
cell_text = []
for row in range(n_rows):
y_offset = y_offset + data[row]
cell_text.append(['%1.1f' % (x/1000.0) for x in y_offset])
cell_text = np.array(cell_text)
cell_colors = np.tile(np.ones_like(cell_text,float)[...,None] -0.5
,(1,1,3))
fig = plt.figure()
axes = fig.add_subplot(111)
the_table = axes.table(cellText=cell_text,
colLabels=columns,
cellColours=cell_colors,
loc='center')
#he_table.properties()['celld'][0,0].get_text().set_fontweight(1000)
the_table.auto_set_font_size(False)
the_table.scale(3, 3)
the_table.set_fontsize(20)
table_prop = the_table.properties()
#fill the transpose or not, if we need col height or row width respectively.
rows_heights = [[] for i in range(len([cells for cells in
table_prop['celld'] if cells[1]==0]))]
cols_widths = [[] for i in range(len([cells for cells in
table_prop['celld'] if cells[0]==0]))]
for cell in table_prop['celld']:
text = table_prop['celld'][(0,0)]._text._text
bounds = table_prop['celld'][cell].get_text_bounds(fig.canvas.get_renderer())
cols_widths[cell[1]].append(bounds[2])
rows_heights[cell[0]].append(bounds[3])
cols_width = [max(widths) for widths in cols_widths]
rows_height = [max(heights) for heights in rows_heights]
for cell in table_prop['celld']:
bounds = table_prop['celld'][cell].get_text_bounds(fig.canvas.get_renderer())
table_prop['celld'][cell].set_bounds(*(bounds[:2]+(1.*cols_width[cell[1]],
1.1*rows_height[cell[0]],
)))
plt.axis('off')
plt.show()
结果如下:
虽然具有文本的单元格正确呈现相应列的宽度和高度,但具有数字的单元格无法实现。解决这个问题的一个明显方法是将cols_width
和rows_height
乘以大于1.是否有人知道为什么会发生这种情况并提供解决方案?
答案 0 :(得分:0)
由于文字位于x = l + (w * (1.0 - self.PAD))
你需要让你的格子2*self.PAD
更大。对于默认值self.PAD = 0.1
,最后一行看起来像
table_prop['celld'][cell].set_bounds(*(bounds[:2]+(1.2*cols_width[cell[1]], ...)))