我有一个用matplotlib呈现的表,如下所示
但是,我很难将表头旋转到45度。
我可以知道该如何解决吗?
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 ()
您可以cell.get_text().set_rotation(45)
在将标题设置为[之后cell.set_facecolor (header_color)
]时旋转文本。但是您需要相应地调整标题单元格的高度。为此,您可以使用cell.set_height(1)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句