【Pythonメモ】matplot(軸目盛りラベルが被る・見切れる、軸ラベルの位置変更)

やりたいこと

before

f:id:iiiiikamirin:20200616062808p:plain

after

f:id:iiiiikamirin:20200616062527p:plain

ときれいにしたい。

参考サイト

qiita.com

qiita.com

bettamodoki.hatenadiary.jp

コード

それぞれ以下の1文で調整

軸目盛りラベルが被る

    ax1.set_xticklabels(MSFE_Series.index, ha = 'left')

軸目盛りラベルが見切れる

    fig.subplots_adjust(bottom = 0.2)

軸ラベルの位置変更

    ax2.yaxis.set_label_coords(1.075, 0.5)

コード全体

def get_graph_pair_corr_ver2(MSFE_Series: pd.Series,
                            MSFE_Series2 : pd.Series,
                  bar_graph_save_path: 'str',
                  graph_title: 'str'):

    fig = plt.figure(figsize=(12, 8))
    fig.suptitle(graph_title, fontsize = 20)
    fig.subplots_adjust(bottom = 0.2)
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()

    ax1.bar(MSFE_Series.index, MSFE_Series.values, color='black')
    ax2.plot(MSFE_Series2.index, MSFE_Series2.values, label = 'actual_corr'
             , color = 'red', linewidth = 2)

    ax1.set_ylabel('MSFE', size = 15)
    ax2.set_ylabel('actual_corr', size = 15, rotation = 270)
    ax1.tick_params(axis='x', rotation=315)
    ax2.yaxis.set_label_coords(1.075, 0.5)
    ax1.set_xticklabels(MSFE_Series.index, ha = 'left')

    fig.savefig(bar_graph_save_path)
    plt.figure()

    return

#  メイン処理
if __name__ == '__main__':


    #  パラメータ等設定
    file_path = 'input/mktdata.csv'
    renew_freq = 1  # 最適比率更新頻度
    calc_period = 36

(略)

    #  MSFE下位30ペア
    low20 = pair_MSFE_corr[:30]
    bar_graph_save_path = 'output/pair_corr_low30.png'
    graph_title = 'corr_pair_low30 MSFE vs actual'
    get_graph_pair_corr_ver2(low20, pair_actual_corr[low20.index], bar_graph_save_path, graph_title)