Saya mencoba memahami bagaimana saya dapat mengatur level alfa di tabel matplotlib. Saya mencoba mengaturnya dengan rcparam global, tetapi tidak yakin bagaimana melakukan itu? (Saya ingin mengubah transparansi dalam warna header). Secara umum saya tidak yakin ini dapat dilakukan secara global, jika tidak, bagaimana saya melewati parameter ke tabel? Thx terlebih dahulu.

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

# Set universal font and transparency
plt.rcParams["font.family"] = "DejaVu Sans"
plt.rcParams['axes.prop_cycle'] = cycler(alpha=[0.5])

raw_data = dict(Simulation=[42, 39, 86, 15, 23, 57],
                SP500=[52, 41, 79, 80, 34, 47],
                NASDAQ=[62, 37, 84, 51, 67, 32],
                Benchmark=[72, 43, 36, 26, 53, 88])

df = pd.DataFrame(raw_data, index=pd.Index(
    ['Sharpe Ratio', 'Sortino Ratio', 'Calmars Ratio', 'VaR', 'CVaR', 'Max DD'], name='Metric'),
                  columns=pd.Index(['Simulation', 'SP500', 'NASDAQ', 'Benchmark'], name='Series'))


def create_table(data, col_width=None, row_height=None, font_size=None,
                 header_color='#000080', row_colors=None, edge_color='w',
                 header_columns=0, ax=None, bbox=None):
    if row_colors is None:
        row_colors = ['#D8D8D8', 'w']
    if bbox is None:
        bbox = [0, 0, 1, 1]
    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')

    ax.axis([0, 1, data.shape[0], -1])

    data_table = ax.table(cellText=data.values, colLabels=data.columns, rowLabels=data.index,
                          bbox=bbox, cellLoc='center', rowLoc='left', colLoc='center',
                          colWidths=([col_width] * len(data.columns)))
    cell_map = data_table.get_celld()
    for i in range(0, len(data.columns)):
        cell_map[(0, i)].set_height(row_height * 0.20)

    data_table.auto_set_font_size(False)
    data_table.set_fontsize(font_size)

    for k, cell in six.iteritems(data_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


ax = create_table(df, col_width=1.5, row_height=0.5, font_size=8)

ax.set_title("Risk Measures", fontweight='bold')

ax.axis('off')

plt.tight_layout()

plt.savefig('risk_parameter_table[1].pdf')

plt.show()
1
whartonone 5 April 2021, 00:32

1 menjawab

Jawaban Terbaik

Anda dapat set_alpha() secara manual pada tabel _cells}.

Jika Anda hanya ingin mengubah header, periksa apakah row == 0 atau col == -1:

def create_table(...):
    ...

    for (row, col), cell in data_table._cells.items():
        if (row == 0) or (col == -1):
            cell.set_alpha(0.5)

    return ax

table with alpha

1
tdy 4 April 2021, 23:38