matplotlib.table.Table类没有记录,很难理解逻辑......
我可以更改字体,但不能更改“horizontalalignment”!
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure(figsize=(20,16))
ax1 = fig.add_subplot(1,1,1)
columns = ["label1","label2","label3"]
cell_text = [['1', '2', '3'], ['4', '5', '6']]
fontname = os.path.join(matplotlib.get_data_path(),
'fonts', 'ttf', 'cmex10.ttf')
fig.subplots_adjust(left=0.02, bottom=0.05, right=0.70, top=0.92)
table=ax1.table(cellText=cell_text,colLabels=columns,loc='right',
colWidths=[.035]*len(columns))
table.set_fontsize(48)
table.scale(1.9,2.5)
for key, cell in table.get_celld().items():
row, col = key
#if row > 0 and col > 0:
cell.get_text().set_horizontalalignment('left') # this should work...
cell.set_text_props(horizontalalignment='left') # this also...
if row ==1:
cell.set_text_props(fontproperties=FontProperties(fname=fontname)) # This does work!
cell.get_text().set_color('#ff0000') # this also works !
fig.show()
print(cell.get_text().get_horizontalalignment()) # this print 'left' as expected. But after a "fig.savefig('image.png')" is prints "right" ...
此代码生成: 我们看到行['1','2','3']使用了奇怪的字体,并且是红色的。 但是标题仍然是“居中的”,表格数据是正确对齐而不是左对齐。
“set_fontsize”“scale”和for循环的顺序略有不同。
matplotlib.table代码在此处阅读:https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/table.py