python - Controlling tick labels alignment in pandas Boxplot within subplots -
for single boxplot, tick labels alignment can controlled so:
import matplotlib.pyplot plt import matplotlib mpl %matplotlib inline fig,ax = plt.subplots() df.boxplot(column='col1',by='col2',rot=45,ax=ax) plt.xticks(ha='right')
this necessary because when tick labels long, impossible read plot if tick labels centered (the default behavior).
now on case of multiple subplots. (i sorry not posting complete code example). build main figure first:
fig,axarr = plt.subplots(ny,nx,sharex=true,sharey=true,figsize=(12,6),squeeze=false)
then comes loop iterates on subplot axes , calls function draws boxplot in each of axes objects:
key,gr in grouped: ix = i/ny # python 2 iy = i%ny add_box_plot(gr,xcol,axarr[iy,ix])
where
def add_box_plot(gs,xcol,ax): gs.boxplot(column=xcol,by=keycol,rot=45,ax=ax)
i have not found way aligned tick labels.
if add plt.xticks(ha='right')
after boxplot command in function, last subplot gets ticks aligned correctly (why?).
if add plt.xticks(ha='right') after boxplot command in function, last subplot gets ticks aligned correctly (why?).
this happens because plt.xticks
refers last active axes. when crate subplots, 1 created last active. access axes opbjects directly(although called . however, not change active axis.gs
or gr
in code, whatever means)
solution 1:
use plt.sca()
set current axis:
def add_box_plot(gs, xcol, ax): gs.boxplot(column=xcol, by=keycol, rot=45, ax=ax) plt.sca(ax) plt.xticks(ha='right')
solution 2:
use axes.set_xticklabels()
instead:
def add_box_plot(gs, xcol, ax): gs.boxplot(column=xcol,by=keycol,rot=45,ax=ax) plt.draw() # may required update labels labels = [l.get_text() l in ax.get_xticklabels()] ax.set_xticklabels(labels, ha='right')
i'm not sure if call plt.draw()
required, if leave out empty labels.
Comments
Post a Comment