Python:使 matplotlib 表的列/行标签加粗

mea*_*ory 3 python matplotlib pandas

我试图弄清楚如何为我正在制作的 matplotlib 表加粗列和行标签。

我已经浏览了不同的表格属性,我可以弄清楚如何设置单个单元格的样式,但不能确定实际的列或行标签。

此外,我不知道如何加粗任何东西……只是字体大小、实际字体和颜色。

有什么帮助吗?

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()
Run Code Online (Sandbox Code Playgroud)

编辑:

想通了,虽然它有点笨重。您可以在“celld”属性中找到列/行标签。然后,您可以使用 .set_text_props(fontproperties = FontProperties(weight = 'bold') 将其设置为粗体。即

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()
Run Code Online (Sandbox Code Playgroud)

Dan*_*ele 9

一个稍微好一点的方法,遵循文档

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'))
Run Code Online (Sandbox Code Playgroud)