J Spen
J Spen

Reputation: 2664

Matplotlib setup for saving figures for publication and reports from interactive plots

I had written a python function to take any current interactive figure and modify the text size of labels and tick labels. Then remove the top and right axis for a more preferred format of the figures for output. Then it outputs the figures. The problem I am having is dealing with setting how big the axes is so the xlabel is maintained on the canvas of the figure so when output it shows up. I know manually when creating an axis one can do this:

ax = plt.axes([0.125,0.2,0.95-0.125,0.95-0.2])

Is there anyway to set these parameters after the figure as been plotted? If so how do I get access or go about modifying it? (Also can it be set in matplotlibrc file?).

Another question pertains to if a figure has a legend:

I usually use this set of legend arguments but how do I set the other specifications after the fact? I've only figured out the ones immediately below:

legArgs = dict(bbox_to_anchor=[.44,1.18], borderpad=0.1, labelspacing=0,
               handlelength=1.8, handletextpad=0.05, frameon=False, ncol=5,
                columnspacing=0.02)
               #ncol,numpoints,columnspacing,title,bbox_transform,prop
leg = ax.legend(tuple(legendLabels),tuple(modFreq),'upper center',**legArgs)
leg.get_title().set_fontsize(tick_size)
leg.set_frame_on(False)
leg.set_bbox_to_anchor([1.1,1.05])
for i in leg.get_texts():
    i.set_fontsize(8)

The full plotting function with auxiliary functions:

def plot_for_publication_output(fig, ax, filename, dir_addition='', 
                                fulldir=None, column_width=1, dpi=600,
                                out_formats=['.eps','.pdf','.png']):
    """
    column_width assumes a standard 2 column width format (default 1 column,
    2 meaning spreads across both columns)
    """
    if fulldir == None:
        store_dir = os.path.expanduser('~/'+'Dropbox/Research/Results/' + dir_addition)
    else:
        store_dir = fulldir

    spineLineWidth = 0.5
    tick_size = 9
    fontlabel_size = 10.5
    mydpi = dpi
    outExt = out_formats
    dashs = ['-.', '-', '--', ':']
    dashes = [(1.5, 0), (3.5, 1.5), (1.5, 1.5, 3,1.5), (1, 1)]
    plot_color = "bgrkcykw"
    fig_width_pt = 246.0 * column_width       # Get this from LaTeX using
                                              # \showthe\columnwidth
    inches_per_pt = 1.0 / 72.27               # Convert pt to inches
    golden_mean = (np.sqrt(5) - 1.0) / 2.0    # Aesthetic ratio
    fig_width = fig_width_pt * inches_per_pt  # width in inches
    fig_height = fig_width * golden_mean      # height in inches
    fig.set_size_inches(fig_width, fig_height)
    plotSetAxisTickLabels(ax, tick_size)
    plotSetAxisLabels(ax, fontlabel_size)
    #params = {'axes.labelsize': fontlabel_size, 'text.fontsize': fontlabel_size,
    #          'legend.fontsize': fontlabel_size, 'xtick.labelsize': tick_size,
    #          'ytick.labelsize': tick_size, 'text.usetex': True,
    #          'figure.figsize': fig_size}
    #plt.rcParams.update(params)
    #ax = plt.axes([0.125, 0.2, 0.95 - 0.125, 0.95 - 0.2])
    set_spineLineWidth(ax,spineLineWidth)
    clear_spines(ax)
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')
    for i in outExt:
        plt.savefig(os.path.join(store_dir, filename) + i, dpi = mydpi)

def clear_spines(ax):
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
def set_spineLineWidth(ax, lineWidth):
    for i in ax.spines.keys():
        ax.spines[i].set_linewidth(lineWidth)
def showOnlySomeTicks(x, pos):
    s = str(int(x))
    if x == 5000:
        return    '5e3'#'%.0e' % x
    return ''
def plotSetAxisTickLabels(ax, size=16):
    for i in ax.xaxis.get_ticklabels():
        i.set_fontsize(size)
    for i in ax.yaxis.get_ticklabels():
        i.set_fontsize(size)

def plotSetAxisLabels(ax, size=16):
    ax.xaxis.get_label().set_fontsize(size)
    ax.yaxis.get_label().set_fontsize(size)

Upvotes: 3

Views: 1653

Answers (1)

stanri
stanri

Reputation: 2972

You can change the axes position using the set_position function:

# save the instance 
ax = plt.axes([0.125,0.2,0.95-0.125,0.95-0.2])

# change the axes position
ax.set_position([0.52, 0.85, 0.16, 0.075])

The documentation for the above command is found in the matplotlib axes documentation.

You can also find functions for the legend instance in legend in the API, which you've probably found, or dig around in the documentation for the child objects, you can call the child functions too in the same manner as you have for this line:

leg.get_title().set_fontsize(tick_size)

Upvotes: 3

Related Questions