Beispiel #1
0
    def __init__(self, ylims=None, num_twiny_axes=2, num_twinx_axes=1):

        # Geometry

        self.ylims = ylims
        self.fig = plt.figure(figsize=(6, 8))
        self.gridspecs = gridspec.GridSpec(
            len(ylims) if ylims else 1,
            1,
            height_ratios=list(reversed([ylim[1] - ylim[0]
                                         for ylim in ylims])))
        self.axes = list(self.create_axes())
        self.twiny_axes = [[ax.twiny() for ax in self.axes]
                           for i in range(num_twiny_axes)]
        self.twinx_axes = [[ax.twinx() for ax in self.axes]
                           for i in range(num_twinx_axes)]
        for axes in [self.axes] + self.twinx_axes:
            for ax, ylim in zip(axes, list(reversed(ylims))):
                ax.set_ylim(*ylim)
            # for twinx_axes in self.twinx_axes:
            #     for ax, ylim in zip(twinx_axes, list(reversed(ylims))):
            #         ax.set_ylim(*ylim)

        # Axes
        #for ax in self.axes[:-1] + self.twin_axes[:-1]:
        for ax in self.axes[:-1] + [
                ax for twiny_axes in self.twiny_axes for ax in twiny_axes[:-1]
        ]:
            #ax.spines['bottom'].set_visible(False)
            ax.spines['bottom'].set_linewidth(.5)
            #ax.spines['bottom'].set_alpha(.5)
            ax.spines['bottom'].set_linestyle('dotted')
            ax.tick_params(labelbottom=False, bottom=False, which='major')
            ax.tick_params(labelbottom=False, bottom=False, which='minor')

        for ax in self.axes[1:] + [
                ax for twiny_axes in self.twiny_axes for ax in twiny_axes[1:]
        ]:
            #ax.spines['top'].set_visible(False)
            ax.spines['top'].set_linewidth(.5)
            #ax.spines['top'].set_alpha(.5)
            ax.spines['top'].set_linestyle('dotted')
            ax.tick_params(labeltop=False, top=False, which='major')
            ax.tick_params(labeltop=False, top=False, which='minor')

        for ax in self.axes + [
                ax for twiny_axes in self.twiny_axes for ax in twiny_axes
        ]:
            #for ax in self.axes + self.twin_axes:
            ax.tick_params(direction='in', which='major')
            ax.tick_params(direction='in', which='minor')
            ax.yaxis.set_major_locator(ticker.MultipleLocator(.1))
            ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
            ax.set_axisbelow(True)
        for ax in self.axes:
            ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
            ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
            ax.grid(ls='-', which='major', lw=1, c='k', alpha=.2)
            ax.grid(ls='-', which='minor', lw=.5, c='k', alpha=.1)
        self.create_diag(.008, .015)
Beispiel #2
0
def plot(data, unit="wn", figname="specden.svg"):

    if unit == "eV":
        x = data[:, 1]
        xlabel = 'E / eV'
        xmaj = ticker.MultipleLocator(0.05)

    elif unit == "wn":
        x = data[:, 0]
        xlabel = r'$\tilde{\nu}$ / cm$^{-1}$'
        xmaj = ticker.MultipleLocator(500)

    specden = data[:, -1]

    # Set up a plot
    fig = plt.figure()
    gs = gridspec.GridSpec(1, 1)
    gs.update(wspace=0.1, hspace=0.1)

    ax = plt.subplot(gs[0])
    ax.plot(x, specden)

    # Plot options
    ax.set_xlabel(xlabel)
    ax.set_ylabel(r'$J(\omega)$ / cm$^{-1}$')

    ax.set_xlim(x.min(), x.max() + 1)
    ax.set_ylim(0)

    xminloc = ticker.AutoMinorLocator(5)
    yminloc = ticker.AutoMinorLocator(5)

    ax.xaxis.set_major_locator(xmaj)
    ax.xaxis.set_minor_locator(xminloc)
    ax.yaxis.set_minor_locator(yminloc)

    #    ax.yaxis.set_label_coords(-0.1, 0.5)

    ax.xaxis.set_ticks_position('both')
    ax.yaxis.set_ticks_position('both')
    ax.tick_params(axis='both',
                   which='major',
                   direction='in',
                   pad=10,
                   length=5)
    ax.tick_params(axis='both',
                   which='minor',
                   direction='in',
                   pad=10,
                   length=2)
    # ax.relim()
    # ax.autoscale_view(True,True,True)
    # ax.set_aspect(0.65/ax.get_data_ratio())
    rcParams.update({'font.size': 18})
    # plt.gcf().subplots_adjust(bottom=0.15)
    plt.savefig(figname, dpi=600)
    plt.close()
    # plt.show()

    return
    def plot_one_psd(ax, X_pwr, f_ax, title_str, p_range, f_range):
        """
        Plots ONLY ONE PSD
        """
        X_plot = 10 * np.log10(X_pwr + np.finfo(float).eps)
        plt.plot(f_ax, X_plot)

        # Major and Minor ticks
        ax = plt.gca()
        ax.xaxis.set_major_locator(ticker.AutoLocator())
        ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
        ax.yaxis.set_major_locator(ticker.AutoLocator())
        ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())

        plt.xlabel('Modulation frequency (Hz)')
        plt.ylabel('Conventional frequency (Hz)')

        if f_range is not None:
            xlim = f_range
        else:
            xlim = f_ax

        if p_range is not None:
            ylim = p_range
        else:
            ylim = X_plot

        # set the limits of the plot to the limits of the data
        plt.axis([xlim.min(), xlim.max(), ylim.min(), ylim.max()])

        plt.title(title_str)
        plt.draw()
Beispiel #4
0
def roc(data):
    '''
    This function generates a standard rate of climb plot.
    Input data must have columns following the standard naming
    convention of the helicopter class.
    
    ie. A dataframe output from the Helicopter.forward_flight method
    can be directly supplied.
    '''
    fig, ax = plt.subplots(figsize=(15,9))

    # Add the data and color it
    ax.plot(data.Airspeed, data.ROC, color='orange', label='Rate of Climb', marker='o', markersize='4')
    ax.legend()

    # Axis labels
    ax.set_xlabel('Airspeed, $V$ [kts]', fontsize=12)
    ax.set_ylabel('Rate of Climb, $ROC$ [ft/min]', fontsize=12)
    ax.set_title('Forward Flight Rate of Climb\n', fontsize=18)

    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax.tick_params(axis='both', which='both', direction='in')

    # Set the grid lines
    ax.grid(b=True, which='major', linestyle=':')
    ax.grid(b=True, which='minor', linestyle=':', alpha=0.3)
    
    return fig, ax
Beispiel #5
0
def plot_box_plot(df, save_dir):
    df.columns = df.columns.swaplevel(0, 1)
    columns = df.columns.levels[0]
    print 'columns', columns
    for c in columns:
        plt.figure(figsize=(7, 5))
        dd = df[c].copy()
        dd.columns = [mapping_dict_cols[a] for a in dd.columns]
        model_names = dd.columns

        avg = dd['P-NET'].median()
        sns.set_style("whitegrid")
        order = list(dd.median().sort_values().index)
        dd = dd.melt()
        ax = sns.boxplot(x="variable", y="value", data=dd, whis=np.inf, order=order, palette=my_pal)
        ax.axhline(avg, ls='--')

        plt.ylim([0.4, 1.05])
        ax.set_ylabel(mapping_dict[c], fontdict=dict(family='Arial', weight='bold', fontsize=14))

        ax.set_xlabel('')
        plt.tight_layout()
        plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right', fontsize=14)
        ax.get_xaxis().set_minor_locator(ticker.AutoMinorLocator())
        ax.get_yaxis().set_minor_locator(ticker.AutoMinorLocator())
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)
        plt.gcf().subplots_adjust(bottom=0.3, left=0.2)
        plt.savefig(join(save_dir, c + '_boxplot'), dpi=100)
Beispiel #6
0
def nclize_axis(ax, minor_per_major=3):
    """
    Utility function to make plots look like NCL plots
    """
    import matplotlib.ticker as tic

    ax.tick_params(labelsize="small")
    ax.minorticks_on()
    ax.xaxis.set_minor_locator(tic.AutoMinorLocator(n=minor_per_major))
    ax.yaxis.set_minor_locator(tic.AutoMinorLocator(n=minor_per_major))

    # length and width are in points and may need to change depending on figure size etc.
    ax.tick_params(
        "both",
        length=8,
        width=1.5,
        which="major",
        bottom=True,
        top=True,
        left=True,
        right=True,
    )
    ax.tick_params(
        "both",
        length=5,
        width=0.75,
        which="minor",
        bottom=True,
        top=True,
        left=True,
        right=True,
    )
Beispiel #7
0
 def plotalgos(self):
     """plots aglos"""
     figure(figsize=self.figsize)
     for i, algo in enumerate(self.algolist):
         d = self.moving_average_pct(self.algos, algo)
         plt.plot(self.blocklist,
                  d,
                  '-',
                  color=self.colorlist[i],
                  label=algo,
                  linewidth=self.lw)
         plt.hold('on')
         plt.grid('on')
         ax = plt.gca()
         ax.get_xaxis().set_minor_locator(ticker.AutoMinorLocator())
         ax.get_yaxis().set_minor_locator(ticker.AutoMinorLocator())
         ax.set_xlim([self.blocklist[0], self.blocklist[-1]])
         ax.grid(b=True,
                 which='major',
                 color='#a0a0a0',
                 linestyle='-',
                 linewidth=1.0)
         ax.grid(b=True,
                 which='minor',
                 color='#dcdcdc',
                 linestyle='-',
                 linewidth=0.5)
         ax.get_xaxis().get_major_formatter().set_scientific(False)
         ax.get_xaxis().get_major_formatter().set_useOffset(False)
         ax.set_xlabel('Block Number')
         ax.set_ylabel('% of Blocks')
     ax.set_title('Block % for Mining Algorithms')
     legend(self.algolist, loc=0, prop={'size': 8})
     savefig(self.plotpath + 'algohist.png', bbox_inches='tight')
Beispiel #8
0
def plot_species(ax, windows, abbrev):
    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))
    ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))
    ax.grid(True, which='both')

    ax.plot(
        windows['window_order'],
        -np.log10(windows['pvalue']),
        linewidth='0.75',
        color='black',
    )
    hotspots = windows.loc[windows['signif'] & windows['top_window']]
    ax.scatter(
        hotspots['window_order'],
        -np.log10(hotspots['pvalue']),
        s=4,
        color='red',
    )
    ax.set_ylabel("-log10(P)")
    title = ax.twinx()
    title.set_ylabel(sp.species_abbrev,
                     bbox={
                         'linestyle': "-",
                         'linewidth': 1,
                         'edgecolor': 'black',
                         'facecolor': 'lightgrey'
                     })
    title.set_yticks([])
    pass
Beispiel #9
0
def animate(i, st, download, upload, time, ax1, ax2):

    # Add x and y to lists
    time.append(dt.datetime.now().strftime("%d/%m/%y %H:%M:%S"))
    download.append(st.download() / 1e6)
    upload.append(st.upload() / 1e6)

    # Draw x and y lists
    ax1.clear()
    ax1.plot(time, download)
    ax2.clear()
    ax2.plot(time, upload)

    # Format plot
    ax1.set_xticks([])
    ax1.yaxis.set_major_locator(ticker.AutoLocator())
    ax1.yaxis.set_minor_locator(ticker.AutoMinorLocator())

    ax2.xaxis.set_major_locator(ticker.AutoLocator())
    ax2.xaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax2.yaxis.set_major_locator(ticker.AutoLocator())
    ax2.yaxis.set_minor_locator(ticker.AutoMinorLocator())

    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    ax1.set_title("Download Speed")
    ax2.set_title("Upload Speed")
    ax1.set_ylabel("Speed (Mb/s")
    ax2.set_ylabel("Speed (Mb/s")
    ax2.set_xlabel("Time")
    plt.tight_layout()
Beispiel #10
0
def global_plot(dic=dataBase, name=False, overlap=False):

    if name is not False: plt.title(list(dic.keys()))

    fig, ax = plt.subplots(1, 1, figsize=(16, 16), dpi=180)

    if overlap is True:
        for linea in dic.keys():
            grafo, z = dic[linea], solapamiento[linea]
            colormap = plt.cm.jet  # plt.cm.hsv
            normalize = matplotlib.colors.Normalize(vmin=1, vmax=22)
            lc = LineCollection(zip(grafo[:-1], grafo[1:]),
                                array=z,
                                cmap=colormap,
                                norm=normalize)
            ax.add_collection(lc)
            ax.margins(0.5, 0.1)
        ax.xaxis.set_major_locator(mticker.MultipleLocator(5))
        ax.yaxis.set_major_locator(mticker.MultipleLocator(5))
        ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(5))
        ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(5))
        ax.grid(which='major', color='#CCCCCC', linestyle='--')
        ax.grid(which='minor', color='#CCCCCC', linestyle=':')
        # plt.grid()
        plt.colorbar(lc, ticks=mticker.MultipleLocator(5), aspect=50)
        plt.xlim([-5, 32]), plt.ylim([32, 72])

    else:
        for linea in dic.keys():
            x, y = [k[0] for k in grafo], [k[1] for k in grafo]
            plt.plot(x, y, '-', linewidth=2, color="b")
            plt.grid()
Beispiel #11
0
def subplots(nrows=1, ncols=1, figsize = (4, 3), sharex=True, \
             sharey=True, **kwargs):

    if nrows == 1 and ncols == 1:

        fig, ax = plt.subplots(figsize=figsize,
                               constrained_layout=True,
                               **kwargs)

        ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))
        ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))
        ax.tick_params(direction='in', length=6)

        return fig, ax

    elif (nrows > 1 and ncols == 1) or (ncols > 1 and nrows == 1):

        fig, axs = plt.subplots(nrows=nrows, ncols=ncols, sharex=sharex, \
                                sharey=sharey, **kwargs)

        for ax in axs:
            ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))
            ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))
            ax.tick_params(direction='in', length=6, labelsize=20)

        return fig, axs

    else:

        fig, ax = plt.subplots(nrows=nrows, ncols=ncols, \
                               sharex=True, sharey=True)

        return fig, ax
def plot_params(ax,
                axis_label=None,
                plt_title=None,
                label_size=15,
                axis_fsize=15,
                title_fsize=20,
                scale='linear'):
    # Tick-Parameters
    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax.tick_params(which='both', width=1, labelsize=label_size)
    ax.tick_params(which='major', length=6)
    ax.tick_params(which='minor', length=3, color='0.8')

    # Grid
    plt.grid(lw=1, ls='-', c="0.7", which='major')
    plt.grid(lw=1, ls='-', c="0.9", which='minor')

    # Plot Title
    plt.title(plt_title, {'fontsize': title_fsize})

    # Yaxis sacle
    plt.yscale(scale)
    plt.minorticks_on()
    # Plot Axes Labels
    xl = plt.xlabel(axis_label[0], fontsize=axis_fsize)
    yl = plt.ylabel(axis_label[1], fontsize=axis_fsize)
Beispiel #13
0
def update_ticks_and_axes(ax, plt, baseFontSize, yAxisFormatString,
                          allowNegativeY, xAxisGridStyle, yAxisGridStyle):

    if not allowNegativeY:
        # Assure that the Y axis minimum is not negative
        ymin, ymax = plt.ylim()

        if ymin < 0:
            plt.ylim(bottom=0)

    # plt.xticks(fontsize=baseFontSize-2)
    # plt.yticks(fontsize=baseFontSize-2)
    ax.yaxis.set_major_formatter(mtick.FormatStrFormatter(yAxisFormatString))
    ax.yaxis.set_minor_locator(mtick.AutoMinorLocator())

    # Optionally define the distance between tick labels
    # ax.xaxis.set_major_locator(mtick.MultipleLocator(5000))
    ax.xaxis.set_major_formatter(
        mtick.FuncFormatter(lambda x, p: format(int(x), ',')))
    ax.xaxis.set_minor_locator(mtick.AutoMinorLocator())

    xAxisGridlines = len(xAxisGridStyle) > 0
    yAxisGridlines = len(yAxisGridStyle) > 0

    if xAxisGridlines or yAxisGridlines:
        ax.grid(True)

        ax.xaxis.grid(xAxisGridlines, which='major', linestyle=xAxisGridStyle)
        ax.xaxis.grid(False, which='minor')

        ax.yaxis.grid(yAxisGridlines, which='major', linestyle=yAxisGridStyle)
        ax.yaxis.grid(False, which='minor')
Beispiel #14
0
def plot_schedulability_rates_simplegen():
    """Plot schedulability rates in a graph, using the results from eval_simplegen()."""
    modes = [
        # name, color, linestyle, marker
        ('dSMC', 'blue', 'dashed', 'o'),
        ('dAMC', 'red', 'dashed', 'd'),
        ('EDF-VD', 'green', 'dashed', 's'),
        ('pSMC', 'orange', 'dashed', '^'),
        ('pAMC-BB', 'magenta', 'dashed', 'D'),
        ('pAMC-BB+', 'purple', 'dashed', 'v')
    ]

    task_sets_list = pickle.load(
        open(task_sets_path + 'task_sets_simplegen', 'rb'))
    rates = {}
    fig = plt.figure(figsize=(12, 6), dpi=300)
    fig.suptitle('Evaluation: SimpleGen (n=%d)' % len(task_sets_list[0]))
    ax1 = fig.add_subplot(111)
    for name, color, linestyle, marker in modes:
        rates[name] = pickle.load(open(eval_simplegen_path + name, 'rb'))
        ax1.plot(utils,
                 rates[name],
                 label=name,
                 color=color,
                 linestyle=linestyle,
                 marker=marker)
    ax1.set_xlabel('LO mode utilization')
    ax1.set_ylabel('Percentage of task sets schedulable')
    ax1.set_xlim(0.1, 2.1)
    ax1.set_xticks([k * 0.5 for k in range(5)])
    ax1.set_yticks([k * 20 for k in range(6)])
    ax1.xaxis.set_minor_locator(ticker.AutoMinorLocator(5))
    ax1.yaxis.set_minor_locator(ticker.AutoMinorLocator(1))
    ax1.minorticks_on()
    ax1.grid(which='both', linestyle='dashed')

    # Plot average system util:
    avg_utils = []
    for i, _ in enumerate(utils):
        avg_utils.append(
            np.average([task_set.u_avg for task_set in task_sets_list[i]]))
    ax2 = ax1.twinx()
    ax2.plot(utils,
             avg_utils,
             label='Avg Sys Util (right scale)',
             color='black',
             linestyle='dashed',
             marker=None)
    ylim = ax1.get_ylim()
    ax2.set_ylim(ylim[0] / 100, ylim[1] / 100)
    ax2.set_ylabel('U(Avg)')

    plt.axvline(1.0, color='black', linewidth=0.8)
    lines1, labels1 = ax1.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    plt.xlim(0.1, 2.1)
    plt.legend(lines1 + lines2, labels1 + labels2, loc='center left')
    plt.savefig('./figures/schedulability_rates_simplegen.png')
def mozenaPlot(data):
    '''
	create the plot from Mark Mozena's thesis with given data
	Sersic vs Reff vs Axis Ratio
	'''
    condition = np.ones_like(data["red"], bool)
    condition &= data["cam"] != 0
    condition &= data["cam"] != 1
    condition &= (data["red"] > 1.4) & (data["red"] < 2.6)
    condition &= (data["mass"] > 10**8.5) & (data["mass"] < 10**11)
    s = 0.5
    ser = data["ser"][condition]
    rad = data["rad"][condition]
    ba = data["ba"][condition]
    serlim = [0, 5.5]
    serticks = [1, 2, 3, 4, 5]

    serVSrad = plt.subplot(221)
    serVSrad.plot(rad, ser, "bs", ms=s)
    serVSrad.set_xscale("log")
    serVSrad.set_ylabel("Sersic (n)", labelpad=15)
    serVSrad.set_ylim(serlim)
    serVSrad.set_yticks(serticks)
    serVSrad.yaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    plt.setp(serVSrad.get_xticklabels(), visible=False)

    baVSrad = plt.subplot(223, sharex=serVSrad)
    baVSrad.plot(rad, ba, "bs", ms=s)
    baVSrad.set_xlabel("$R_{eff}$ (kpc)")
    baVSrad.set_xscale("log")
    baVSrad.set_xlim(0.5, 12)
    baVSrad.set_xticks([1.0, 3.0, 10.0])
    baVSrad.xaxis.set_major_formatter(ticker.LogFormatter(labelOnlyBase=False))
    baVSrad.set_ylabel("Axis Ratio (q)")

    baVSser = plt.subplot(224, sharey=baVSrad)
    baVSser.plot(ser, ba, "bs", ms=s)
    baVSser.set_xlim(serlim)
    baVSser.set_xticks(serticks)
    baVSser.xaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    baVSser.set_xlabel("Sersic (n)")
    baVSser.set_ylim(0, 1.05)
    baVSser.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0])
    baVSser.yaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    plt.setp(baVSser.get_yticklabels(), visible=False)

    # remove extra space between subplots
    plt.tight_layout(w_pad=0, h_pad=0)

    # these are matplotlib.patch.Patch properties
    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
    # place a text box in upper left in axes coords
    textstr = "Simulations\nFour Random Cameras\n$z = 1.4 - 2.6$"
    textstr += "\n$log(M_{\odot}) = 8.5 - 11.0$\n$N = %d$" % len(ser)
    plt.figtext(0.6, 0.9, textstr, fontsize=16,
                verticalalignment='top')  #, bbox=props)
    return
Beispiel #16
0
def plot2DTrial(X, Y, C, ax=plt.gca(), xlabel=None, ylabel=None,
                colorBar=False, clBarLabel="", vmin=None, vmax=None, title="",
                clbarNTicks=2, xticks=True, yticks=True, cmap=None, cbar_kw={},
                sliceAnn=None, axis_setting='scaled', **kw):
    '''A low level function to plot a 2D trial-average data into a plot.'''
    kw['rasterized'] = kw.get('rasterized', True)
    cbar_kw['label']       = cbar_kw.get('label', '')
    cbar_kw['shrink']      = cbar_kw.get('shrink', 0.8)
    cbar_kw['pad']         = cbar_kw.get('pad', 0.05)
    cbar_kw['ticks']       = cbar_kw.get('ticks', ti.MultipleLocator(5))
    cbar_kw['rasterized']  = cbar_kw.get('rasterized', True)

    if xlabel is None:
        xlabel = xlabelText
    if ylabel is None:
        ylabel = ylabelText

    dx = X[0, 1] - X[0, 0]
    dy = Y[1, 0] - Y[0, 1]

    globalAxesSettings(ax)
    ax.minorticks_on()
    mappable = ax.imshow(C, vmin=vmin, vmax=vmax, cmap=cmap,
                         extent=(X[0, 0] - dx / 2., X[0, -1] + dx / 2.,
                                 Y[0, 0] - dy / 2., Y[-1, 0] + dy / 2.),
                         interpolation='none',
                         origin='lower',
                         **kw)
    cax = createColorbar(ax, mappable=mappable, **cbar_kw)
    if colorBar == False:
        cax.set_visible(False)
    if xlabel != "":
        ax.set_xlabel(xlabel, va='top')
        ax.xaxis.set_label_coords(0.5, -0.125)
    if ylabel != "":
        ax.set_ylabel(ylabel, ha='center')
        ax.yaxis.set_label_coords(-0.125, 0.5)
    ax.xaxis.set_ticks([X[0, 0], X[0, -1]])
    ax.yaxis.set_ticks([Y[0, 0], Y[-1, 0]])
    ax.xaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.yaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.axis(axis_setting)
    if not xticks:
        ax.xaxis.set_ticklabels([])
    if not yticks:
        ax.yaxis.set_ticklabels([])

    # slice annotations
    if sliceAnn is not None:
        for args in sliceAnn:
            args.update(ax=ax, X=X, Y=Y)
            plotSliceAnnotation(**args)


    return C, ax, cax
def _heatmap(features,clen,step,Plot,**kwargs):
    reg=kwargs.get('reg',None)
    if reg:
       lo=reg[0]
       hi=reg[1]
    else:
       lo=0
       hi=clen

    ranges=_heat(features,lo,hi,step)

    import numpy as np
    x=np.array(_arrpoints(lo,hi,step))
    y=np.array([value for value in ranges.values()])
    maxy=max([value for value in ranges.values()])
    medy=__roundup((maxy/2),1)
    if Plot.num_ax==4:
       ax_heat=Plot.ax3
       ax_curve=Plot.ax4
    elif Plot.num_ax==3:
       ax_heat=Plot.ax2
       ax_curve=Plot.ax3

    extent = [x[0]-(x[1]-x[0])/2., x[-1]+(x[1]-x[0])/2.,0,1]
    ax_heat.xaxis.set_minor_locator(ticker.AutoMinorLocator())
    _heatmap=ax_heat.imshow(y[np.newaxis,:], cmap="plasma", aspect="auto", extent=extent)
    ax_heat.set_yticks([])
    ax_heat.set_xlim(extent[0], extent[1])
 
    axins = inset_axes(ax_heat,
                           width="1%",  # width = 5% of parent_bbox width
                           height="100%",  # height : 50%
                           loc='center left',
                           bbox_to_anchor=(-0.011, 0, 1, 1),
                           bbox_transform=ax_heat.transAxes,
                           borderpad=0,
                           )
    
    cbar = ax_heat.figure.colorbar(_heatmap,
                                   cax=axins,
                                   orientation='vertical',
                                   fraction=.25,
                                   ticks=[0,maxy])
    cbar.ax.yaxis.set_ticks_position('left') 
    cbar.ax.yaxis.set_tick_params(labelsize=9)
    
    ax_curve.plot(x,y)
    ax_curve.set_xlim(extent[0], extent[1])
    ax_curve.xaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax_curve.set_yticks([0,medy,maxy])
    ax_curve.yaxis.set_tick_params(labelsize=9)
    ax_curve.set_ylabel(f'Variant count per\n{step} bp',
                        fontsize='small',
                        labelpad=-0.4,
                        va='bottom')
Beispiel #18
0
    def __init__(self, parent=None, id: int = None, types: List[CurveType] = [], params: Dict = FIGURE_CONF) -> None:
      # Canvas Attributes
        self.fig, _ = plt.subplots(constrained_layout=True)
        super(MyCanvasItem, self).__init__(self.fig)
        self.id = id
        self.parameter = params.copy()
        self.parameter["Title"] = f"%s | %s" % (types[0].value, types[1].value)

        self.wg_canvas = parent

        self.ax_types = types
        self.ax_main = self.fig.axes[0]
        self.ax_sub = self.fig.axes[0].twinx()
        self.ax_sub.set_zorder(1)
        self.ax_main.set_zorder(2)
        self.ax_main.patch.set_visible(False)
        self.grid_status = [True, False]
        self.update_axis_info()

        self.apply_style()

        self.draggable_lines = [Draggable_lines(
            self, self.ax_main), Draggable_lines(self, self.ax_sub)]
        self.draggable_lines[0].set_visible(False)
        self.draggable_lines[1].set_visible(False)

      # Interation functions with canvas
        self.setAcceptDrops(True)
        # self.fig.canvas.mpl_connect('pick_event', self.handle_pick)
        self.fig.canvas.mpl_connect(
            'button_press_event', self.handleDoubleClicked)
        self.fig.canvas.mpl_connect('button_press_event', self.handle_click)

      # Default Setting

        self.ax_main.format_coord = lambda x, y: ""
        self.ax_main.set_ylim(auto=False)
        self.ax_main.grid(linewidth='0.75', linestyle='-', color='black')
        self.ax_main.grid(which='minor',
                          linewidth='0.5', linestyle=':', color='#808080')
        self.ax_main.yaxis.set_minor_locator(ticker.AutoMinorLocator(5))

        self.ax_sub.set_visible(False)
        self.ax_sub.set_ylim(auto=False)
        self.ax_sub.grid(linewidth='0.75', color='#1f77b4',
                         linestyle='dashed', dashes=(20, 10))
        self.ax_sub.grid(which='minor',
                         linewidth='0.5', color='#8fbbd9', linestyle='--', dashes=(10, 5))
        self.ax_sub.yaxis.set_minor_locator(ticker.AutoMinorLocator(5))

        self.set_grid_status()

        self.fig.set_constrained_layout_pads(w_pad=10/72., h_pad=10/72.,
                                             hspace=0.5, wspace=0.5)
Beispiel #19
0
def spectrum(spec, color_ions=True, annotate_ions=True, ax=None):
    if ax is None:
        ax = plt.gca()

    max_intensity = spec.intensity.max()
    for mz, intensity, annotation in zip(spec.mz, spec.intensity,
                                         spec.annotation):
        ion_type = annotation.ion_type if annotation is not None else None
        color = colors.get(ion_type) if color_ions else colors.get(None)
        zorder = zorders.get(ion_type)

        ax.plot([mz, mz], [0, intensity / max_intensity],
                color=color,
                zorder=zorder)

        if annotate_ions and annotation is not None:
            ax.text(mz + 5,
                    intensity / max_intensity + 0.02,
                    str(annotation),
                    color=color,
                    zorder=5,
                    rotation=90,
                    rotation_mode='anchor')

    min_mz = max(0, math.floor(spec.mz[0] / 100 - 1) * 100)
    max_mz = math.ceil(spec.mz[-1] / 100 + 1) * 100
    ax.set_xlim(min_mz, max_mz)
    ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.))
    ax.set_ylim(0, 1.15 if annotate_ions else 1.05)

    ax.xaxis.set_minor_locator(mticker.AutoLocator())
    ax.yaxis.set_minor_locator(mticker.AutoLocator())
    ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
    ax.yaxis.set_minor_locator(mticker.AutoMinorLocator())
    ax.grid(b=True,
            which='major',
            color='#9E9E9E',
            linestyle='--',
            linewidth=1.0)
    ax.grid(b=True,
            which='minor',
            color='#9E9E9E',
            linestyle='--',
            linewidth=0.5)
    ax.set_axisbelow(True)

    ax.tick_params(axis='both', which='both', labelsize='small')

    ax.set_xlabel('m/z')
    ax.set_ylabel('Intensity')

    return ax
Beispiel #20
0
def adjust(axis,
           title="",
           loc=0,
           minor=[True, False, False, False],
           xlim=[],
           ylim=[],
           xlabel="Time (s)",
           ylabel="",
           xVisible=True,
           yVisible=True,
           seperator=True):
    """ Adjust axis properties
    """
    axis.set_title(title)
    if isinstance(loc, int): axis.legend(loc=loc)

    if minor[0]:  # X ticks minorlocator
        axis.xaxis.set_minor_locator(ticker.AutoMinorLocator())
        if minor[1]:  # X minor axis
            axis.grid(which='minor', axis='x', color='tab:gray', linestyle=':')
    if minor[2]:  # Y ticks minorlocator
        axis.yaxis.set_minor_locator(ticker.AutoMinorLocator())
        if minor[3]:  # Y minor axis
            axis.grid(which='minor', axis='y', color='tab:gray', linestyle=':')
    if minor != [False, False, False, False]:
        axis.grid(which='major')

    if xlim != []:
        if len(xlim) == 2:
            axis.set_xlim(xlim[0], xlim[1])
        if len(xlim) == 3:
            axis.set_xlim(xlim[0], xlim[1])
            axis.set_xticks(numpy.arange(xlim[0], xlim[1] + xlim[2], xlim[2]))
    if ylim != []:
        if len(ylim) == 2:
            axis.set_ylim(ylim[0], ylim[1])
        if len(ylim) == 3:
            axis.set_ylim(ylim[0], ylim[1])
            axis.set_yticks(numpy.arange(ylim[0], ylim[1] + ylim[2], ylim[2]))

    axis.set_xlabel(xlabel)
    axis.set_ylabel(ylabel)

    if not xVisible: plt.setp(axis.get_xticklabels(), visible=False)
    if not yVisible: plt.setp(axis.get_yticklabels(), visible=False)

    # use " " as thousand seperator
    if seperator:
        axis.yaxis.set_major_formatter(
            ticker.FuncFormatter(
                lambda x, pos: format(int(x), ",").replace(",", " ")))
Beispiel #21
0
    def Histogram(self,
                  y,
                  title=' ',
                  xLabel=' ',
                  yLabel=' ',
                  dump=False,
                  **kwargs):
        """
        Histogram plot

        Inputs:
          - bins = list of bin edges
          - y = 1D array

        Options:
          - title = plot title, string
          - xLabel = title of the x-axis, string
          - yLabel = title of the y-axis, string
          - dump = boolean, dump profile data in csv file
          - kwargs = keyword options associated with pandas.DataFrame.to_csv, such as:
                     sep, header, na_rep, index,...etc
                     Check doc. of "to_csv" for complete list of options
        """
        ## the histogram of the data
        #fig = plt.figure(figsize=(18,10))
        self._def_fig()
        self._ax = self._fig.add_subplot(111)
        density, bins = np.histogram(y, bins=50, normed=True, density=True)
        unity_density = density / density.sum()
        widths = bins[:-1] - bins[1:]
        # To plot correct percentages in the y axis
        self._ax.bar(bins[1:], unity_density, width=widths)
        formatter = ticker.FuncFormatter(lambda v, pos: str(v * 100))
        self._ax.yaxis.set_major_formatter(formatter)
        self._ax.get_xaxis().set_minor_locator(ticker.AutoMinorLocator())
        self._ax.get_yaxis().set_minor_locator(ticker.AutoMinorLocator())
        self._ax.grid(b=True, which='major', color='w', linewidth=1.5)
        self._ax.grid(b=True, which='minor', color='w', linewidth=0.5)

        plt.ylabel(yLabel)
        plt.xlabel(xLabel)

        self._fig.show()

        if dump:
            self._dump_profile_data_as_csv(bins[1:],
                                           unity_density,
                                           title=title,
                                           xLabel=xLabel,
                                           yLabel=yLabel,
                                           **kwargs)
    def _setspineslabels(self):
        self.ax1.spines['top'].set_visible(False)  #equivalent to ax1.set_frame_on(False)
        self.ax1.spines['right'].set_visible(False)
        self.ax1.spines['left'].set_visible(False)

        self.ax1.xaxis.set_minor_locator(ticker.AutoMinorLocator())
        self.ax1.axes.get_yaxis().set_visible(False)

        if self.ax2:
           self.ax2.spines['top'].set_visible(False)  #equivalent to ax1.set_frame_on(False)
           self.ax2.spines['right'].set_visible(False)
           self.ax2.spines['left'].set_visible(False)
           self.ax2.xaxis.set_minor_locator(ticker.AutoMinorLocator())
           self.ax2.axes.get_yaxis().set_visible(False)
def graph_std(climate, cities, w_length=1):
    """
    Plot the std for a given city across the years.

    Args:
        climate: a climate object.
        city: a str or list of str of cities names in capital letters.
        w_length: compute the moving average of temperatures with
        specified window length of years.

    Retunrs:
        A seaborn lineplot of (14x6) inches of std temperatures vs years.
    """
    years = climate.get_years()
    # Filtering the data frame by cities, months, days
    temps = climate.filter_by(cities=cities)

    # std value of the period temperatures remaining constant every year.
    y = np.array(
        [temps[temps.index.year == year].values.min() for year in years])
    z = np.array(
        [temps[temps.index.year == year].values.max() for year in years])

    # Computing the moving average and seting up the data frame.
    y = main.moving_average(y, w_length)
    z = main.moving_average(z, w_length)
    w = z - y
    df = pd.DataFrame({'YEAR': years, 'MIN': y, 'MAX': z, 'Delta': w})

    # Minimal and Maximal temperatures after all the averages
    temp_min, temp_max = -30, 52

    fig, ax = plt.subplots(figsize=(14, 6))
    ax = sns.lineplot(x='YEAR', y='MIN', data=df, linewidth=4)
    ax = sns.lineplot(x='YEAR', y='MAX', data=df, linewidth=4)
    ax.fill_between(x='YEAR', y1=temp_min, y2=temp_max, data=df, alpha=0.25)

    ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(10))
    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(5))
    ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(5))
    ax.grid(which='major', color='#CCCCCC', linestyle='--')
    ax.grid(which='minor', color='#CCCCCC', linestyle=':')

    ax.set_xlim(min(df.YEAR), max(df.YEAR))
    ax.set_ylim(temp_min, temp_max)
    ax.set_xlabel(None)
    ax.set_ylabel('Temperature (ºC)')
    # ax.set_title(title, size=20)
    ax.grid(axis='x', c='gray', ls='--')
Beispiel #24
0
def plotConnHistogram(val, **kw):
    '''
    Plot a histogram of connection weights with some predetermined formatting.

    Parameters
    ----------
    val : numpy array
        A 1D array of connetions.
    **kw
        Keyword arguments to the hist function. See code for some additional
        keyword arguments.
    '''
    # keyword arguments
    kw['bins'] = kw.get('bins', 20)
    #kw['edgecolor'] = kw.get('edgecolor', 'none')
    ax = kw.pop('ax', plt.gca())
    xlabel = kw.pop('xlabel', 'g (nS)')
    ylabel = kw.pop('ylabel', 'Count')
    title = kw.pop('title', '')
    locators = kw.pop('locators', {})
    ylabelPos = kw.pop('ylabelPos', -0.2)

    globalAxesSettings(ax)
    n, _, _ = ax.hist(val, **kw)
    print(np.max(n))
    ax.set_xlabel(xlabel)
    ax.text(ylabelPos,
            0.5,
            ylabel,
            rotation=90,
            transform=ax.transAxes,
            va='center',
            ha='right')
    ax.set_title(title)

    # tick formatting
    x_major = locators.get('x_major', ti.MaxNLocator(3))
    x_minor = locators.get('x_minor', ti.AutoMinorLocator(2))
    y_major = locators.get('y_major', ti.LinearLocator(2))
    y_minor = locators.get('y_minor', ti.AutoMinorLocator(4))
    ax.xaxis.set_major_locator(x_major)
    ax.yaxis.set_major_locator(y_major)
    ax.xaxis.set_minor_locator(x_minor)
    ax.yaxis.set_minor_locator(y_minor)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

    return ax
Beispiel #25
0
def plot_1d_sweep(data, ax, xlabel, ylabel, xticks=True, yticks=True,
                  axis_setting='scaled', title='', **kwargs):
    '''Plot a 1D parameter Sweep.

    Parameters
    ----------
    data : AggregateData
        Data to plot. The first (Y/rows) dimension will be ignored.
    ax : mpl.Axes
        Matplotlib axes.
    xlabel, ylabel : str
        X/Y label strings
    xticks, yticks : bool
        Whether to plot ticks and number on the X/Y axes.
    kwargs : dict
        Keyword arguments that will be passed on to the plot function.
    '''
    plot_data, X, _ = data.getTrialData()
    X = X.flatten()

    logger_1d.info('min(data): %f', np.min(plot_data.flatten()))
    logger_1d.info('max(data): %f', np.max(plot_data.flatten()))

    globalAxesSettings(ax)
    ax.minorticks_on()

    if xlabel != "":
        ax.set_xlabel(xlabel, va='top')
        ax.xaxis.set_label_coords(0.5, -0.125)
    if ylabel != "":
        ax.set_ylabel(ylabel, ha='center')
        ax.yaxis.set_label_coords(-0.125, 0.5)

    ax.plot(X.flatten(), plot_data[0, :, :], 'o', color='g', markersize=5,
            markeredgecolor='white', **kwargs)
    if xlabel != "":
        ax.set_xlabel(xlabel, va='top')
        ax.xaxis.set_label_coords(0.5, -0.125)
    if ylabel != "":
        ax.set_ylabel(ylabel, ha='center')
        ax.yaxis.set_label_coords(-0.157, 0.5)
    ax.xaxis.set_ticks([X[0], X[-1]])
    ax.xaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.yaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.axis(axis_setting)
    if not xticks:
        ax.xaxis.set_ticklabels([])
    if not yticks:
        ax.yaxis.set_ticklabels([])
Beispiel #26
0
def drawConcurrentUsersPlot(axes, nb_users_list, stat_list, only_average=False):
  min_array = numpy.array([stat.minimum for stat in stat_list])
  mean_array = numpy.array([stat.mean for stat in stat_list])
  max_array = numpy.array([stat.maximum for stat in stat_list])

  yerr_list = [stat.standard_deviation for stat in stat_list]
  yerr_lower = numpy.minimum(mean_array - min_array, yerr_list)
  yerr_upper = numpy.minimum(max_array - mean_array, yerr_list)

  axes.errorbar(nb_users_list,
                mean_array,
                yerr=[yerr_lower, yerr_upper],
                color='r',
                ecolor='b',
                label='Mean',
                elinewidth=2,
                fmt='D-',
                capsize=10.0)

  if not only_average:
    axes.plot(nb_users_list, min_array, 'yo-', label='Minimum')
    axes.plot(nb_users_list, max_array, 'gs-', label='Maximum')

  axes.set_xticks(nb_users_list)

  return (ticker.FixedLocator(nb_users_list), None,
          ticker.MaxNLocator(nbins=20), ticker.AutoMinorLocator())
def render_plot(file_path: str):
    # xaxis configuration: Major ticks every month, minor ticks every week (+ these can overlap).
    plt.gca().xaxis.set_remove_overlapping_locs(False)
    plt.gca().xaxis.set_major_locator(dates.MonthLocator())
    plt.gca().xaxis.set_major_formatter(dates.DateFormatter('%Y-%m'))
    plt.gca().xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=0))

    # xaxis configuration: Customize tick labels alignment for a subjectively more readable result.
    for tick in plt.gca().get_xticklabels():
        tick.set_ha('left')

    # yaxis configuration: Major ticks every hour, minor ticks every 10 minutes.
    plt.gca().yaxis.set_major_locator(ticker.MultipleLocator(1))
    plt.gca().yaxis.set_minor_locator(ticker.AutoMinorLocator(6))

    # yaxis configuration: Start at 0 to avoid displaying negative time.
    plt.ylim(bottom=0)

    # Grid configuration.
    plt.grid(b=True, which='major', linestyle='--')
    plt.grid(b=True, which='minor', linestyle=':', alpha=GRID_ALPHA)

    # Legend configuration.
    legend_elements = []
    for k, v in SLEEP_TIME_TYPES.items():
        legend_elements.append(
            lines.Line2D([0], [0], color=v['color'], label=v['label']))
    plt.legend(handles=legend_elements)
    plt.xlabel('Date')
    plt.ylabel('Sleep time (h)')

    plt.savefig(file_path)
Beispiel #28
0
    def plot(self, file):
        """ Plot energy convergence curve """

        plt.figure()
        plt.plot([*self.__best_gener, self.generation],
                 [*self.__best_curve, self.best_fit],
                 color="#222222",
                 label="Energy",
                 lw=0.5)

        sciargs = {"style": "sci", "scilimits": (0, 0), "useMathText": True}

        ax = plt.gca()

        gargs = {"axis": "y", "ls": ":"}

        # Add minor locators
        ax.yaxis.set_minor_locator(tck.AutoMinorLocator())

        # Add grids
        plt.grid(True, which="minor", lw=0.1, color="#CCCCCC", **gargs)
        plt.grid(True, which="major", lw=0.5, color="#AAAAAA", **gargs)

        # Use scientific notiation on x-axis
        plt.ticklabel_format(axis="x", **sciargs)

        # Use scientific notiation on y-axis
        plt.ticklabel_format(axis="y", **sciargs)

        plt.xlabel("Generation")
        plt.ylabel("Fitness")
        plt.legend()

        plt.savefig(file, dpi=300, transparent=True)
        plt.close()
def plot_rpr_curve(sor, params, compare=False, rp=[], save=False):
    # Defining Matplotlib Figure
    f = plt.figure(num=None, figsize=(9, 12))

    sor_range = np.arange(sor.min() - 2, sor.max() + 2)
    rpr = get_rpr(sor_range, params)

    # Sub plot
    ax = f.add_subplot(111)

    if compare:
        # Plotting actual data
        plt.scatter(sor, rp, s=50, marker='o', label='Actual data')
        # Plotting calculated data
        plt.scatter(sor,
                    get_rpr(sor, params),
                    s=70,
                    marker='x',
                    label='Value calculated by equation')

    plt.plot(sor_range, rpr, c='g')

    # Semi-Log Plot
    plt.yscale("log")

    # Setting Plot Tick-values
    plt.yticks([0.01, 0.001, 0.01, 0.1, 1, 10, 100])
    plt.xticks(np.arange(sor.min() // 10 * 10, 101, 10))

    # Tick-Parameters
    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax.tick_params(which='both', width=1, labelsize=14)
    ax.tick_params(which='major', length=6)
    ax.tick_params(which='minor', length=3, color='0.8')

    # Plot Title
    if compare:
        plt.title("Permeability Ratio Data\n (Actual vs Calculated)",
                  {'fontsize': 20})
    else:
        plt.title("Permeability Ratio Data", {'fontsize': 20})

    # Plot Axes Labels
    axis_label = ["Oil Saturation (So) in persent(%)", "Kg/Ko"]
    xl = plt.xlabel(axis_label[0], fontsize=16)
    yl = plt.ylabel(axis_label[1], fontsize=16)

    if compare:
        # Legend Location
        plt.legend(loc="best")

    # Grid
    plt.grid(lw=1, ls='-', c="0.7", which='major')
    plt.grid(lw=1, ls='-', c="0.9", which='minor')

    #saving plot
    if save:
        plt.savefig("KoKgRatioVsSaturtion_curve.png")
    # Showing Final Plot
    plt.show()
Beispiel #30
0
def plot_box_plot(df, axis):
    df.columns = df.columns.swaplevel(0, 1)
    metrics = df.columns.levels[0]
    print 'metrics', metrics
    for i, c in enumerate(metrics):
        dd = df[c].copy()
        dd.columns = [mapping_dict_cols[a] for a in dd.columns]
        avg = dd['P-NET'].median()
        sns.set_style("whitegrid")
        order = list(dd.median().sort_values().index)
        dd = dd.melt()
        # ax = sns.boxplot(ax=axis[i], x="variable", y="value", data=dd, whis=np.inf, order=order, palette=my_pal, linewidth=1)
        flierprops = dict(marker='o', markersize=1, alpha=0.7)

        ax = sns.boxplot(ax=axis[i], x="variable", y="value", data=dd, whis=1.5, order=order, palette=my_pal,
                         linewidth=1, flierprops=flierprops)
        ax.axhline(avg, ls='--', linewidth=1)
        ax.set_ylim([0.4, 1.05])
        ax.set_ylabel(mapping_dict[c], fontproperties)
        ax.set_xlabel('')
        ax.set_xticklabels(ax.get_xticklabels(), rotation=30, horizontalalignment='right', fontsize=fontsize)
        ax.get_xaxis().set_minor_locator(ticker.AutoMinorLocator())
        ax.tick_params(axis='both', which='major', labelsize=fontsize)
        ax.minorticks_off()
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.spines['left'].set_visible(False)