I have a table rendered with matplotlib as shown below
But, I am having difficulties in rotating the table header to, say 45 degree.
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. But you would need to adjust the height of the header cell accordingly. For that you can use cell.set_height(1)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.