gpt4 book ai didi

python - 表格中的 Matplotlib 文本对齐

转载 作者:行者123 更新时间:2023-12-02 15:09:30 25 4
gpt4 key购买 nike

我正在努力正确地左/右对齐文本,而不会在列中浪费空间。中心/左/右使用相同的列宽度:

  1. Center aligned : 正确居中,ok
  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()

最佳答案

默认情况下,单元格两侧有 10% 的填充,这有助于让文本开始靠近表格单元格边框。对于非常大的单元格,10% 太多了,会导致不需要的大空间。

enter image description here

为了克服这个问题,需要将相关列的填充设置为较低的值,因为对于所有其他列,10% 实际上是可取的。没有用于设置填充的内置选项,但可以通过遍历列的单元格并更改相应的 PAD 属性来操纵它。

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

set_pad_for_column(col=1, pad=0.01)

这仅为第二列 (col=1) 生成 1% 的填充。

enter image description here

关于python - 表格中的 Matplotlib 文本对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44798364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com