簡體   English   中英

如何在 Matplotlib 中旋轉表頭?

[英]How to rotate table header in Matplotlib?

目標是使用 df 中的 Matplotlib 創建一個表。 然后,我希望標題(日期、卡路里、睡眠時間)旋轉 90 度。

最初,我認為這可以通過訪問每個標簽並使用label.set_rotation(90)旋轉它來label.set_rotation(90) 然而,它並沒有像預期的那樣實現。

我可以知道如何解決這個問題嗎?

完整代碼如下

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import six

df = pd.DataFrame ()
df ['date'] = ['2016-04-01', '2016-04-02', '2016-04-03']
df ['calories'] = [2200, 2100, 1500]
df ['sleep hours'] = [2200, 2100, 1500]
df ['gym'] = [True, False, False]

def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
                     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) ])

    for label in ax.get_xticklabels():
        # https://stackoverflow.com/a/43153984/6446053
        label.set_ha("right")
        label.set_rotation(90)

    return ax

    render_mpl_table (df, header_columns=0, col_width=2.0)
    
    plt.show ()

提前致謝。

您可以像這樣在標題行中設置文本屬性rotation

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import six

df = pd.DataFrame ()
df ['date'] = ['2016-04-01', '2016-04-02', '2016-04-03']
df ['calories'] = [2200, 2100, 1500]
df ['sleep hours'] = [2200, 2100, 1500]
df ['gym'] = [True, False, False]

def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,
                     header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
                     bbox=[0, 0, 1, 1], header_columns=0, header_height=2.0,
                     ax=None, **kwargs):
    if ax is None:
        size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])
        size[1] += header_height - 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)
            cell.set_text_props(rotation='vertical')
            cell.set_height(header_height)
        else:
            cell.set_facecolor(row_colors[k[0]%len(row_colors) ])
            cell.set_height(row_height)


    return ax

render_mpl_table (df, header_columns=0, col_width=2.0, header_height=2.0)
    
plt.show ()

在此處輸入圖片說明

請注意,我在示例中手動調整了行高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM