Matplotlib表格的字体大小

5
在Python (2.7.9)中使用Matplotlib。我必须在一个子图中绘制一个表格(在这种情况下,子图名称为tab),但似乎找不到改变表格字体大小的方法(http://imgur.com/0Ttvzee - 左下角)。蚁人对结果感到满意,而我却不是。 这是我一直在使用的代码。
def stat_chart(self):

DN      = self.diff
ij      = self.ij_list
mcont   = self.mcont
ocont   = self.ocont
ucont   = self.ucont
dist    = self.widths
clon    = '%1.2f' %self.mclon
clat    = '%1.2f' %self.mclat
clonlat = "{0}/{1}".format(clon,clat)
area    = self.area
perim   = self.perimeter
mdist   = np.array(self.widths)
mdist   = mdist[:,0]*10
mdist   = np.mean(mdist)
pstat   = self.polygon_status
if pstat == 1:
  status = "Overestimation"
else:
  status = "Underestimation"

# Setting up the plot (2x2) and subplots
fig   = plt.figure()
gs    = gridspec.GridSpec(2,2,width_ratios=[2,1],height_ratios=[4,1])
main  = plt.subplot(gs[0,0])
polyf = plt.subplot(gs[0,1])
tab   = plt.subplot(gs[1,0])
leg   = plt.subplot(gs[1,1])
tab.set_xticks([])
leg.set_xticks([])
tab.set_yticks([])
leg.set_yticks([])
tab.set_frame_on(False)
leg.set_frame_on(False)

# Main image on the top left
main.imshow(DN[::-1],cmap='winter')
x1,x2,y1,y2 = np.min(ij[:,1])-15,np.max(ij[:,1])+15,np.min(ij[:,0])-15,np.max(ij[:,0])+15
main.axvspan(x1,x2,ymin=1-((y1-320)/float(len(DN)-320)),ymax=1-((y2-320)/float(len(DN)-320)),color='red',alpha=0.3)
main.axis([0,760,0,800])

# Polygon image on the top right
polyf.imshow(DN,cmap='winter')
polyf.axis([x1,x2,y2,y1])
polyf.plot(mcont[:,1],mcont[:,0],'ro',markersize=4)
polyf.plot(ocont[:,1],ocont[:,0],'yo',markersize=4)
polyf.plot(ucont[:,1],ucont[:,0],'go',markersize=4)
for n,en in enumerate(dist):
  polyf.plot([en[2],en[4]],[en[1],en[3]],color='grey',alpha=0.3)

# Legend on the bottom right
mc = mlines.Line2D([],[],color='red',marker='o')
oc = mlines.Line2D([],[],color='yellow',marker='o')
uc = mlines.Line2D([],[],color='green',marker='o')
ed = mlines.Line2D([],[],color='black',alpha=0.5)
pos_p = mpatches.Patch(color='lightgreen')
neg_p = mpatches.Patch(color='royalblue')
leg.legend([mc,oc,uc,ed,pos_p,neg_p],("Model Cont.","Osisaf Cont.","Unknown Cont.","Dist. Mdl to Osi", \
  'Model Overestimate','Model Underestimate'),loc='center')

# Statistics table on the bottom left
stats = [[clonlat+' degrees' ,'%1.4E km^2' %area,'%1.4E km' %perim,'%1.4f km' %mdist,status]]
columns = ('Center Lon/Lat','Area','Perimeter','Mean Width','Status')
rows = ['TODOpolyname']
cwid = [0.1,0.1,0.1,0.1,0.1,0.1]
the_table = tab.table(cellText=stats,colWidths=cwid,rowLabels=rows,colLabels=columns,loc='center')
table_props = the_table.properties()
table_cells = table_props['child_artists']
for cell in table_cells: cell.set_height(0.5)
plt.show()

return

编辑2:最终解决了将文本绘制成表格的问题。已经足够好了。

如果你经常做这种事情,你可能想考虑通过networkx将数据导出为shapefile,并在QGIS中创建图表。当涉及到管理多个地图和表格时,QGIS的打印组合器确实让matplotlib相形见绌。 - mmdanziger
谢谢,但我不是一个好的程序员(正如你可以从这令人羞愧的脚本中看到的),而且我的时间不多了。现在正在学习QGIS,转移所有内容需要太多时间。不过,将来它是一个很棒的工具。谢谢。 - GDino
2个回答

15

我在更改字体大小时遇到了类似的问题。请尝试以下方法:

the_table.auto_set_font_size(False)
the_table.set_fontsize(5.5)

对我有用。


1
尝试此解决方案时出现以下错误:AttributeError: 'NoneType' object has no attribute 'set_fontsize' - D.L
如果你遇到了这个错误,但是在 the_table.auto_set_font_size(False) 上没有出现错误,那么你可能做了类似于 the_table = the_table.auto_set_font_size(False) 的操作,因为这样确实会将 the_table 设置为 None。否则第二行就不会出现 NoneType 错误。 - hugovdberg

2
根据文档table有一个名为fontsize的关键字参数,表示以点为单位的浮点数大小。
在您上面的示例中,如果要使用5点大小的字体,可以使用以下代码:
    the_table =tab.table(cellText=stats,colWidths=cwid,rowLabels=rows,colLabels=columns,loc='center',fontsize=5)

如果您需要更大的控制权,可以像这个例子中描述的那样,将FontManager实例传递给cell.set_text_props()方法。 这将使您能够设置字体系列、间距、样式等,除了大小之外。
编辑:尝试使用Matplotlib的示例时,似乎只是将fontsize传递给表格没有效果。 但是,导入
    from matplotlib.font_manager import FontProperties

然后循环遍历单元格并运行。
    cell.set_text_props(fontproperties=FontProperties(size = 5))

具有预期效果。目前不清楚为什么文档中记录的 kwarg 参数 fontsize 在此处(或者在您的情况下)似乎无法使用。

2
尝试过了。没有起作用。结果完全一样。 - GDino
@GDino 两种方法都用了吗?你是在使用 pyplot.table 还是 ax.add_table?你能提供一个包含导入和所有内容的最小可运行示例吗? - mmdanziger
查看编辑后的答案: 对于 the_table.get_celld().items() 中的每个键和单元格: 获取行号 row 和列号 col。 如果 row > 0 且 col > 0,则设置字体属性为 FontProperties(size=50)。 仍然无法正常工作。不管怎样,谢谢。 - GDino
@GDino,使用for key, cell in tab.get_celld().items():迭代单元格是否有任何区别? - mmdanziger
刚刚做了,结果还是一样。:( - GDino
目前,我建议您尝试将表格绘图移到单独的图形中,看看能否确定问题的源头,并尝试重新组合并进行调试。或者只需分开生成,然后在下游进行合并。 - mmdanziger

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