Matplotlib 表格格式化列宽

新手上路,请多包涵

我希望格式化表格的一列,但是在遍历行时,每次迭代后,列宽的宽度都会发生变化。

源代码

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

格式化前

在此处输入图像描述

不幸的是,在迭代之后:

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

看起来单元格宽度增加了,结果如下:

格式化后

在此处输入图像描述

任何关于为什么会发生这种情况的建议,或者调整宽度的替代解决方案将不胜感激!

原文由 Justin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

试试我的 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 源代码。

输出

原文由 Yuri Xu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题