Chris McLean
Chris McLean

Reputation: 31

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()

Upvotes: 3

Views: 6324

Answers (1)

Remy F
Remy F

Reputation: 1529

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

Upvotes: 4

Related Questions