Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: making column/row labels of matplotlib table bold

I'm trying to figure out how to bold the column and row labels for a matplotlib table I'm making.

I've gone through the different table properties, and I can figure out how to style the individual cells, but not the actual columns or row labels.

Further, I'm not able to find out how to bold anything.. just font size, actual font, and color.

Any help?

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

fig, axs =plt.subplots(figsize = (10,6))
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs.axis('tight')
axs.axis('off')

df = pd.DataFrame(np.random.randn(10, 4), 
                  columns=['a','b','c','d'], 
                  index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])

table = axs.table(cellText=df.values, colLabels = df.columns, rowLabels = df.index,  loc='center')

plt.show()

EDIT:

Figured it out, though it's kind of clunky. You can find the columns/row labels in the "celld" property. You can then set it to bold using .set_text_props(fontproperties = FontProperties(weight = 'bold'). i.e.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import pandas as pd

fig, axs =plt.subplots(figsize = (10,6))
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs.axis('tight')
axs.axis('off')

df = pd.DataFrame(np.random.randn(10, 4), 
                  columns=['a','b','c','d'], 
                  index = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])


table = axs.table(cellText=df.values, colLabels = df.columns, rowLabels = df.index,  loc='center')


P = []

for key, cell in table.get_celld().items():
    row, col = key
    P.append(cell)

for x in P[40:]:
    x.set_text_props(fontproperties=FontProperties(weight='bold'))

plt.show()
like image 200
measure_theory Avatar asked Dec 18 '22 20:12

measure_theory


1 Answers

A slightly better method, following the documentation:

from matplotlib.font_manager import FontProperties

for (row, col), cell in table.get_celld().items():
  if (row == 0) or (col == -1):
    cell.set_text_props(fontproperties=FontProperties(weight='bold'))
like image 96
Daniele Avatar answered Dec 28 '22 22:12

Daniele