Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply formatting to cell contents in Matplotlib table

I am relatively new to python/Matplotlib. I am trying to work out how I can control the number of decimal places displayed in a table cell.

For example; Here is a block of code that creates a table.. but I want the data in each cell only be displayed to two decimal places..

from pylab import *

# Create a figure
fig1 = figure(1)
ax1_1 = fig1.add_subplot(111)

# Add a table with some numbers....
the_table = table(cellText=[[1.0000, 3.14159], [sqrt(2), log(10.0)], [exp(1.0), 123.4]],colLabels=['Col A','Col B'],loc='center')    
show()
like image 770
Chris McLean Avatar asked Jan 19 '26 11:01

Chris McLean


1 Answers

You can convert your number using the string formater to do what you want: '%.2f' % your_long_number for a float (f) with two decimals (.2) for example. See this link for the documentation.

from pylab import *

# Create a figure
fig1 = figure(1)
ax1_1 = fig1.add_subplot(111)

# Add a table with some numbers....

tab = [[1.0000, 3.14159], [sqrt(2), log(10.0)], [exp(1.0), 123.4]]

# Format table numbers as string
tab_2 = [['%.2f' % j for j in i] for i in tab]

the_table_2 = table(cellText=tab_2,colLabels=['Col A','Col B'],loc='center') 

show()

Result:

enter image description here

like image 173
Remy F Avatar answered Jan 21 '26 09:01

Remy F