5

Working with Matplotlib in Python (2.7.9). I have to plot a table in a subplot (in this case subplot name is tab) but I can't seem to find a way to change the font size of the table (https://i.stack.imgur.com/TToAa.jpg - bottom left). Antman is happy about the results, I am not. This is the code I've been using.

EDIT: Added full code

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

EDIT2: Eventually (un)solved plotting text instead of table. Good enough.

GDino
  • 93
  • 2
  • 2
  • 8
  • If you do a lot of this kind of thing, you may want to consider exporting your data to shapefile (via eg, networkx) and creating your plots in QGIS. The QGIS print composer really puts matplotlib to shame when it comes to managing multiple maps and tables. – mmdanziger Jun 09 '15 at 09:33
  • Thanks but I'm not a good programmer (as you can see from the shameful script) and I'm running out of time. Learning QGIS now and transferring everything would take too much time. For the future though it's a great tool. Thanks. – GDino Jun 09 '15 at 10:10
  • possible duplicate of [How to change the table's fontsize with matplotlib.pyplot?](http://stackoverflow.com/questions/15514005/how-to-change-the-tables-fontsize-with-matplotlib-pyplot) – user Jun 26 '15 at 12:35

2 Answers2

15

I had a similar issue in changing the fontsize. Try the following

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

Worked for me.

user2750362
  • 382
  • 3
  • 6
  • 1
    get this error when trying this solution: `AttributeError: 'NoneType' object has no attribute 'set_fontsize'` – D.L Aug 13 '20 at 18:33
  • If you get that error, but don't get the error on `the_table.auto_set_font_size(False)` you probably did something like `the_table = the_table.auto_set_font_size(False)`, as that indeed would set `the_table` to None. Otherwise it makes no sense the second line would raise the error on `NoneType`. – hugovdberg Jun 25 '21 at 11:11
2

According to the docs, table has a kwarg called fontsize, a float value for the size in points.

In your example from above, for a fontsize of 5 points you would use:

    the_table =tab.table(cellText=stats,colWidths=cwid,rowLabels=rows,colLabels=columns,loc='center',fontsize=5)

If you require greater control, you can pass a FontManager instance to the cell.set_text_props() method as described in this example. That would enable you to set the family, spacing, style etc, in addition to the size.

EDIT: Playing around with Matplotlib's example, it seems that just passing fontsize to the table has no effect. However, importing

    from matplotlib.font_manager import FontProperties

and then looping through the cells and running

    cell.set_text_props(fontproperties=FontProperties(size = 5))

does have the desired effect. It is unclear why the documented kwarg fontsize does not work in this (or apparently in your) case.

mmdanziger
  • 4,466
  • 2
  • 31
  • 47
  • 2
    Tried it. Didn't work. The result is exactly the same. – GDino Jun 09 '15 at 09:11
  • @GDino both methods? Are you using `pyplot.table` or `ax.add_table` ? Could you provide a MWE with imports and everything? – mmdanziger Jun 09 '15 at 09:17
  • Looked the edited answer: for key, cell in the_table.get_celld().items(): row, col = key if row > 0 and col > 0: cell.set_text_props(fontproperties=FontProperties(size=50)) still not working. Thanks anyway. – GDino Jun 09 '15 at 09:49
  • @GDino Does iterating through the cells canonically as `for key, cell in tab.get_celld().items():` make any difference? – mmdanziger Jun 09 '15 at 10:09
  • Just did, same result. :( – GDino Jun 09 '15 at 10:32
  • At this point, I would only suggest that you try and move the table plot to a separate figure, see if you can determine the source of the problem and try and recombine it and debug. Or just generate it separately and combine it downstream. – mmdanziger Jun 09 '15 at 10:45