toshiakiasakura / contextplt

Context manager style of matpotlib.
MIT License
0 stars 0 forks source link

ticklabel fontsize settings is not reflected if specified inside context manager. #15

Closed toshiakiasakura closed 2 years ago

toshiakiasakura commented 2 years ago

Bug reproducing code.

def timeseries_heatmap(df : pd.DataFrame, time_col : str, c : str) -> None:

    df_ht = pd.crosstab(df[time_col], df[c])
    df_ht_per = pd.crosstab(df[time_col], df[c], normalize="index")*100
    # to impute non-existing years.
    for i in range(df_ht.index.min(), df_ht.index.max() + 1 ):
        if i not in df_ht.index:
            df_ht.loc[i] = 0
            df_ht_per.loc[i] =np.nan 
    df_ht = df_ht.sort_index()
    df_ht_per = df_ht_per.sort_index()

    tick_size=6
    with cplt.Multiple(grid=(1,2), figsize=(8,4)) as mul:
        with cplt.MulSingle(mul=mul, index=1,title="Count", 
                            xtickfontsize=tick_size, ytickfontsize=13,
                           ) as p:
            ht = sns.heatmap(df_ht, ax=p.ax, cmap="Reds", fmt=".0f",
                            annot=True, linewidths=.2, annot_kws={"fontsize":6})
            ht.set_xticklabels(ht.get_xmajorticklabels(), fontsize = tick_size)
            ht.set_yticklabels(ht.get_ymajorticklabels(), fontsize = tick_size)

        with cplt.MulSingle(mul=mul, index=2,title="Percentage", 
                            xtickfontsize=6, ytickfontsize=6
                           ) as p:
            ht = sns.heatmap(df_ht_per, ax=p.ax, cmap="Reds", fmt=".1f",
                            annot=True, linewidths=.2, annot_kws={"fontsize":6})
df = sm.datasets.get_rdataset("Melanoma", "MASS").data
# Change elements name for good visualization.
df["sex"] = df["sex"].replace({0:"female", 1:"male"})
time_col = "year"
c = "sex"
timeseries_heatmap(df, time_col, c)
toshiakiasakura commented 2 years ago

Use keyword arguments for mul.SIngle parameters. It's difficult for me to accomondate tickfontsize adjustment inside contextmanagers. Good rule of thumb for this package is to use keyword arguments for Single/Multiple class to adjust figure parameters.