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()
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With