Python:将matplotlib表的列/行标签设为粗体

时间:2018-09-20 16:17:24

标签: python pandas matplotlib

我正在尝试找出如何加粗我正在制作的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()

编辑:

弄清楚了,尽管有点笨拙。您可以在“ 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()

1 个答案:

答案 0 :(得分:2)

遵循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'))