我在 matplotlib 中创建了一个表格,但表格标题是长字符串,表格值是只有几位数字的数字。这给我留下了两个糟糕的选择:要么我的表格比需要的宽得多,要么我的标题重叠。要解决此问题,我想旋转表格标题(可能高达 90 度)。换句话说,我想做 this在 python 中
现在这是我的简化代码:
import matplotlib, numpy
import matplotlib.pyplot as plt
data=numpy.array([[1, 2],[3,4]])
headings=['long heading 1', 'long heading 2']
fig=plt.figure(figsize=(5,2))
ax=fig.add_subplot(111, frameon=False, xticks=[], yticks=[])
the_table = plt.table(cellText=data, rowLabels=headings, colLabels=headings, colWidths=[0.3]*data.shape[1], loc='center') #0.3 for second image, 0.03 for first
#the_table.auto_set_font_size(False) #comment out for second image
#the_table.set_fontsize(10) #comment out for second image
the_table.scale(1, 1.6)
plt.show()
这会生成压缩图像或超宽图像(均如下所示)。在我的实际代码中,表格约为 30 x 30,因此单元格不能太宽。有谁知道如何旋转列标题来解决这个间距问题?
请您参考如下方法:
我想通了。它不漂亮,但它有效。我为每一列添加了两个注释 - 文本,以及将它与下一列标题分开的一行。我必须定义一些适用于表格和精美标签(宽度、高度、col_width)的参数,以及一些使精美标签正确排列的参数。此解决方案在我的 30x30 table 上运行良好。
import matplotlib, numpy
import matplotlib.pyplot as plt
width=5
height=3
col_width=.075
data=numpy.array([[1, 2,5],[3,4,7],[7,9,5]])
headings=['long heading 1', 'long heading 2', 'longish 3']
fig=plt.figure(figsize=(width,height))
ax=fig.add_subplot(111, frameon=False, xticks=[], yticks=[])
the_table = plt.table(cellText=data, rowLabels=headings,
colWidths=[col_width]*data.shape[1], loc='center') #remove colLabels
the_table.auto_set_font_size(False)
the_table.set_fontsize(10)
the_table.scale(1, 1.6)
#custom heading titles - new portion
hoffset=0.42 #find this number from trial and error
voffset=0.66 #find this number from trial and error
line_fac=0.98 #controls the length of the dividing line
count=0
for string in headings:
ax.annotate(' '+string, xy=(hoffset+count*col_width,voffset),
xycoords='axes fraction', ha='left', va='bottom',
rotation=45, size=10)
#add a dividing line
ax.annotate('', xy=(hoffset+(count+0.5)*col_width,voffset),
xytext=(hoffset+(count+0.5)*col_width+line_fac/width,voffset+line_fac/height),
xycoords='axes fraction', arrowprops={'arrowstyle':'-'})
count+=1
plt.show()
