Python Pandas Align text in cells

Viewed 2105

How do I align the text in the cells so it will be centered?

Code:

import matplotlib.pyplot as plt
from pandas.tools.plotting import table
import pandas as pd

#My dataframe
df = pd.DataFrame({
    'Weeks' : [201605, 201606, 201607, 201608],
    'Computer1' : [50, 77, 96, 100],
    'Computer2' : [50, 79, 100, 80],
    'Laptop1'   : [75, 77, 96, 95],
    'Laptop2'   : [86, 77, 96, 40],
    'Phone'     : [99, 99, 44, 85],
    'Phone2'    : [93, 77, 96, 25],
    'Phone3'    : [94, 91, 96, 33]
})
df2 = df.set_index('Weeks') #Makes the column 'Weeks' the index.

#Make a png file out of an dataframe.
plt.figure(figsize=(9,3))
ax = plt.subplot(211, frame_on=False) # no visible frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis
colors = df2.applymap(lambda x: 'green' if x>= 80 else 'red').reset_index().drop(['Weeks'], axis=1)
tbl = table(ax, df2, loc='center',
            cellColours=colors.as_matrix(),
            colColours=['black']*len(colors.columns),
            rowColours=['black']*len(colors))
tbl._cells[1, -1]._text.set_color('white')
tbl._cells[2, -1]._text.set_color('white')
tbl._cells[3, -1]._text.set_color('white')
tbl._cells[4, -1]._text.set_color('white')

tbl._cells[0, 0]._text.set_color('white')
tbl._cells[0, 1]._text.set_color('white')
tbl._cells[0, 2]._text.set_color('white')
tbl._cells[0, 3]._text.set_color('white')
tbl._cells[0, 4]._text.set_color('white')
tbl._cells[0, 5]._text.set_color('white')
tbl._cells[0, 6]._text.set_color('white')

plt.show()

This is how it currently looks, and as you can see all the numbers are aligned to the right (and they have to be centered) enter image description here

1 Answers
Related