[英]How to rotate the Matplotlib table header to certain degree?
I have a table rendered with matplotlib as shown below我有一个用 matplotlib 渲染的表格,如下所示
But, I am having difficulties in rotating the table header to, say 45 degree.但是,我在将表头旋转到 45 度时遇到了困难。
May I know how can I fix this?我可以知道如何解决这个问题吗?
import six
import pandas as pd
import numpy as np
def render_mpl_table (data, col_width=1.0, row_height=0.625, font_size=8,
header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
bbox=[0, 0, 1, 1], header_columns=0,
ax=None, **kwargs):
if ax is None:
size = (np.array (data.shape [::-1]) + np.array ([0, 1])) * np.array ([col_width, row_height])
fig, ax = plt.subplots (figsize=size)
ax.axis ('off')
mpl_table = ax.table (cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)
mpl_table.auto_set_font_size (False)
mpl_table.set_fontsize (font_size)
for k, cell in six.iteritems (mpl_table._cells):
cell.set_edgecolor (edge_color)
if k [0] == 0 or k [1] < header_columns:
cell.set_text_props (weight='bold', color='w')
cell.set_facecolor (header_color)
else:
cell.set_facecolor (row_colors [k [0] % len (row_colors)])
return ax
df = pd.DataFrame ({'Label': ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'],
'Month': ['Type 1', 'Type 1', 'Type 2', 'Type 2', 'Type 3',
'Type 1', 'Type 3', 'Type 1', 'Type 2'],
'Activity': ['cc', 'cc', 'tt', 'cc', 'tt', 'tt', 'bb', 'bb', 'cc', ]})
tt = pd.crosstab (index=[df ['Activity']], columns=[df ['Label'], df ['Month']], margins=True)
tab_me = render_mpl_table (tt, header_columns=0, col_width=2.0)
plt.show ()
You can use cell.get_text().set_rotation(45)
when you set your header [after cell.set_facecolor (header_color)
] to rotate the text.当您设置标题 [after
cell.set_facecolor (header_color)
] 时,您可以使用cell.get_text().set_rotation(45)
来旋转文本。 But you would need to adjust the height of the header cell accordingly.但是您需要相应地调整标题单元格的高度。 For that you can use
cell.set_height(1)
.为此,您可以使用
cell.set_height(1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.