Matplotlib表格格式化列宽

10

我希望能够对表格的一列进行格式化,但是在迭代行时,每次迭代后,该列的宽度似乎都会发生变化。

源代码

def p_create_table(self, events, dates, rows, columns, portfolio):
    """
    :param events: Dict - {Date:Event} where Event is a String identifying
    what event happened
    :param dates: List - Dates of events
    :param rows: Int - number of Dates (rows) to create for the table
    :param columns: List - Column headers
    :param portfolio: Dataframe - Portfolio with calculated totals and returns
    :return:
    """
    cell_text = self.p_create_cell_text(events, dates, portfolio)
    cell_text.pop(0)
    row_labels = self.p_create_row_labels(rows)
    row_labels.pop(len(row_labels) - 1)
    colors = self.p_set_table_colors(row_labels)

    table = plt.table(cellText=cell_text, cellColours=colors[0],
              rowColours=colors[1], rowLabels=row_labels,
              colColours=colors[2], colLabels=columns,
              bbox=[0.0, -1.3, 1.0, 1.0], cellLoc='center')

    table.auto_set_font_size(False)
    table.set_fontsize(9)
    table.scale(2, 2)

    cell_dict = table.get_celld()
    for i in range(13):
        cell_dict[(i,1)].set_width(0.3)

以下是调整大小之前的表格图像。该快照是在执行 table.set_fontsize(9) 后拍摄的。我想调整第二列 Event 的大小。

格式化之前

enter image description here

不幸的是,在每次迭代后:

for i in range(13):
    cell_dict[(i,1)].set_width(0.3)

看起来单元格宽度增加了,导致出现了这样的情况:

格式化之后

enter image description here

对于为什么会发生这种情况,或者调整宽度的其他解决方案,欢迎提出建议!

3个回答

25

除了@jma的回答之外,我发现表格方法.auto_set_column_width(col=<列索引列表>)非常有用,特别是与.auto_set_font_size(False)结合使用。以下是示例用法:

from matplotlib import pyplot as plt
import pandas as pd
# Create some example data
data = [{"Movie": "Happy Gilmore", "Lead Actor": "Adam Sandler" , "Year": "1996", 
              "Plot": "An ice hockey star takes up golfing.", 
              "Quotes": "\"Just give it a little tappy. Tap tap taparoo.\""}]
dff = pd.DataFrame(data)
fig, ax = plt.subplots(3,1, figsize=(10,4))

tab0 = ax[0].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[0].set_title("Default")
tab1 = ax[1].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[1].set_title("Font AutoSize off")
tab2 = ax[2].table(cellText=dff.values, colLabels=dff.columns, loc='center', cellLoc='center')
ax[2].set_title("Column Width Auto Set, Font AutoSize off")
[a.axis("off") for a in ax]
[t.auto_set_font_size(False) for t in [tab1, tab2]]
[t.set_fontsize(8) for t in [tab1, tab2]]

tab2.auto_set_column_width(col=list(range(len(dff.columns)))) # Provide integer list of columns to adjust
plt.show()

Output


我发现运行代码后第三个表格列宽没有自动调整,我的第三个表格看起来和第二个一样。我错过了什么吗?@Sam Jett - Lisa
@Lisa,你能否把你的代码作为一个例子发出来吗?请确保包含这一行 - tab2.auto_set_column_width(col=list(range(len(dff.columns)))) - 这是使第三个表格与第二个不同的那一行。 - Sam Jett
1
嘿,我刚想到了,我在使用旧版的Matplotlib @ Sam Jett。 - Lisa
2
有没有类似的方式来调整特定行的高度? - olenscki

11

要设置列的宽度,请在table函数中使用colWidths。它接受每个列的宽度列表--它们可以全部相同或不同。

table = plt.table(cellText=cell_text, cellColours=colors[0],
          rowColours=colors[1], rowLabels=row_labels,
          colColours=colors[2], colLabels=columns,
          colWidths=[0.3 for x in columns],
          bbox=[0.0, -1.3, 1.0, 1.0], cellLoc='center')

4

试用我的plot_table版本

data = [{"Movie": "Happy Gilmore", "Lead Actor": "Adam Sandler" , "Year": "1996", 
              "Plot": "An ice hockey star takes up golfing.", 
              "Quotes": "\"Just give it a little tappy. Tap tap taparoo.\""}]
df = pd.DataFrame(data)
data = np.vstack((df.columns.values, df.values.astype(str)))

plot_table(data);

点击此处获取plot_table源代码。

输出结果


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接