def setup_axes(fig, header):
    from mpl_toolkits.axes_grid import make_axes_locatable

    ax0 = pywcsgrid2.subplot(111, wcs=header)
    divider = make_axes_locatable(ax0)

    gh1 = pywcsgrid2.GridHelperSimple(wcs=header, axis_nums=[0, 2])
    ax_v = divider.new_vertical(1.5, pad=0.1, sharex=ax0,
                                axes_class=pywcsgrid2.Axes,
                                grid_helper=gh1)
    fig.add_axes(ax_v)

    gh2 = pywcsgrid2.GridHelperSimple(wcs=header, axis_nums=[2, 1])
    ax_h = divider.new_horizontal(1.5, pad=0.1, sharey=ax0,
                                axes_class=pywcsgrid2.Axes,
                                grid_helper=gh2)

    fig.add_axes(ax_h)


    ax_h.axis["left"].toggle(label=False, ticklabels=False)
    ax_v.axis["bottom"].toggle(label=False, ticklabels=False)


    return ax0, ax_v, ax_h
def drawmap(DATA,TITLESTRING,PROD,UNITS):
    F = plt.gcf()  # Gets the current figure

    m.drawstates(color='k', linewidth=1.25)
    m.drawcoastlines(color='k')
    m.drawcountries(color='k', linewidth=1.25)
	#m.readshapefile(shapefile='/data/geog/shapefiles/fe_2007_40_county.shp',name='COUNTY',drawbounds='True')
	#m.readshapefile(shapefile='/data/geog/shapefiles/fe_2007_48_county.shp',name='COUNTY',drawbounds='True')
	#plt.suptitle('%s' % UNITS, fontsize = 11, x = 0.08, y = 0.105)
    plt.title('UW WRF-ARW %s (%s)   Valid: %s' % (TITLESTRING, UNITS, curtimestring), \
		fontsize=11,bbox=dict(facecolor='white', alpha=0.65),\
		x=0.5,y=.95,weight = 'demibold',style='oblique', \
		stretch='normal', family='sans-serif')

    # Code to make the colorbar outside of the main axis, on the bottom, and lined up
    ax = plt.gca()  # Gets the current axes
    divider = make_axes_locatable(ax)  # Lets us move axes around
    cax = divider.append_axes("bottom", size="2%",pad=-0.02,axes_class=maxes.Axes) # Adds an axis for the colorbar
    F.add_axes(cax)  # Adds the new axis to the figure as the current working axis
    bar = plt.colorbar(DATA,cax=cax,orientation='horizontal',format='%4.2f',extend='both') # Plots colorbar in new axis 
    bar.ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(base=1.0)) # Make the colorbars numbers nice
    bar.update_ticks()

    file_id = '%s_%s_f%02d' % (dom, PROD, time+restart_time)
    filename = '%s.png' % (file_id)
	
    plt.savefig(filename,bbox_inches='tight') # Saves the figure with small margins
    plt.close()

    #if export_flag == 1:
    # Convert the figure to a gif file
    os.system('convert -render -flatten %s %s.gif' % (filename, file_id))
    os.system('rm -f %s' % filename)
Exemple #3
0
def plot(axes, net):

    classname = net.__class__.__name__

    axes.set_xticks([])
    axes.set_yticks([])
    divider = make_axes_locatable(axes)
    subaxes = divider.new_vertical(1.0, pad=0.4, sharex=axes)
    fig.add_axes(subaxes)
    subaxes.set_xticks([])
    subaxes.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
    subaxes.yaxis.set_ticks_position('right')
    subaxes.set_ylabel('Distortion')
    subaxes.set_xlabel('Time')

    Y = net.distortion[::1]
    X = np.arange(len(Y))/float(len(Y)-1)
    subaxes.plot(X,Y)

    if classname == 'NG':
        plt.title('Neural Gas', fontsize=20)
    elif classname == 'SOM':
        plt.title('Self-Organizing Map', fontsize=20)
    elif classname == 'DSOM':
        plt.title('Dynamic Self-Organizing Map', fontsize=20)

    axes.axis([0,1,0,1])
    axes.set_aspect(1)

    codebook = net.codebook
    axes.imshow(codebook, interpolation='nearest')
                         #interpolation='bicubic')

    if classname == 'NG':
        axes.text(0.5, -0.01,
                  r'$\lambda_i = %.3f,\lambda_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
    if classname == 'SOM':
        axes.text(0.5, -0.01,
                  r'$\sigma_i = %.3f,\sigma_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
    elif classname == 'DSOM':
        axes.text(0.5, -0.01,
                  r'$elasticity = %.2f$' % (net.elasticity),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
Exemple #4
0
def demo_images_side_by_sied(ax):
    from mpl_toolkits.axes_grid import make_axes_locatable
    divider = make_axes_locatable(ax)
    Z, extent = get_demo_image()
    ax2 = divider.new_horizontal(size="100%", pad=0.05)
    fig1 = ax.get_figure()
    fig1.add_axes(ax2)
    ax.imshow(Z, extent=extent, interpolation="nearest")
    ax2.imshow(Z, extent=extent, interpolation="nearest")
    for tl in ax2.get_yticklabels():
        tl.set_visible(False)
    def plot_dist(self, axes):
        ''' Plot network on given axes
        '''

        classname = self.__class__.__name__
        fig = plt.gcf()
        divider = make_axes_locatable(axes)
        axes.axis([0,1,0,.5])


        Y = self.distortion[::1]
        X = np.arange(len(Y))/float(len(Y)-1)
        axes.plot(X,Y)
Exemple #6
0
def demo_locatable_axes_easy(ax):
    from mpl_toolkits.axes_grid import make_axes_locatable
    divider = make_axes_locatable(ax)
    ax_cb = divider.new_horizontal(size="5%", pad=0.05)
    fig1 = ax.get_figure()
    fig1.add_axes(ax_cb)
    Z, extent = get_demo_image()
    im = ax.imshow(Z, extent=extent, interpolation="nearest")
    plt.colorbar(im, cax=ax_cb)
    ax_cb.yaxis.tick_right()
    for tl in ax_cb.get_yticklabels():
        tl.set_visible(False)
    ax_cb.yaxis.tick_right()
Exemple #7
0
def QC_Chromosome_Plot(calls, title=None, outfile=None):
    x = np.array(calls.calls["num_probes"].values)
    y = np.array(calls.calls["median_svdzrpkm"].values)

    fig = plt.figure(1, figsize=(9,9))

    from mpl_toolkits.axes_grid import make_axes_locatable

    axScatter = plt.subplot(111)
    divider = make_axes_locatable(axScatter)

    # create a new axes with a height of 1.2 inch above the axScatter
    axHistx = divider.new_vertical(1.2, pad=0.1, sharex=axScatter)

    # create a new axes with a width of 1.2 inch on the right side of the
    # axScatter
    axHisty = divider.new_horizontal(1.2, pad=0.1, sharey=axScatter)

    fig.add_axes(axHistx)
    fig.add_axes(axHisty)

    # make some labels invisible
    plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
             visible=False)

    # the scatter plot:
    #axScatter.scatter(x[x<0], y[x<0], lw=0, alpha=0.3, color="r")
    axScatter.scatter(x[x>=0], y[x>=0], lw=0, alpha=0.3, color="b")
    #axScatter.set_aspect(1.)
    axScatter.set_xscale("symlog")
    axHistx.set_xscale("symlog")

    axScatter.set_xlabel("Size of call (# of probes)")
    axScatter.set_ylabel("Signal Strength (Median SVD-ZRPKM)")

    axHistx.hist(x, bins=np.arange(0,np.max(x)), histtype="stepfilled", lw=0,align='left')
    axHisty.hist(y, bins=200, orientation='horizontal', histtype="stepfilled", lw=0)

    for tl in axHistx.get_xticklabels():
        tl.set_visible(False)

    axHisty.set_xticklabels(["%d" % i for i in axHisty.get_xticks()], rotation=-90)
    if title is not None:
        axHistx.set_title(title)

    if outfile is not None:
        plt.savefig(outfile)
Exemple #8
0
def _stabilityassessment(headers, data1d, dist, fig_correlmatrices, correlmatrixaxes, std_multiplier,
                         correlmatrix_colormap,
                         correlmatrix_filename, logarithmic_correlmatrix=True, cormaptest=True):
    # calculate and plot correlation matrix
    cmatrix, badidx, rowavg = correlmatrix(data1d, std_multiplier, logarithmic_correlmatrix)
    rowavgmean = rowavg.mean()
    rowavgstd = rowavg.std()
    writemarkdown('#### Assessing sample stability')
    writemarkdown("- Mean of row averages: " + str(rowavgmean))
    writemarkdown("- Std of row averages: " + str(rowavgstd) + ' (%.2f %%)' % (rowavgstd / rowavgmean * 100))

    img = correlmatrixaxes.imshow(cmatrix, interpolation='nearest', cmap=matplotlib.cm.get_cmap(correlmatrix_colormap))
    cax = make_axes_locatable(correlmatrixaxes).append_axes('right', size="5%", pad=0.1)
    fig_correlmatrices.colorbar(img, cax=cax)
    fsns = [h.fsn for h in headers]

    correlmatrixaxes.set_title('%.2f mm' % dist)
    correlmatrixaxes.set_xticks(list(range(len(data1d))))
    correlmatrixaxes.set_xticklabels([str(f) for f in fsns], rotation='vertical')
    correlmatrixaxes.set_yticks(list(range(len(data1d))))
    correlmatrixaxes.set_yticklabels([str(f) for f in fsns])
    np.savez_compressed(correlmatrix_filename,
                        correlmatrix=cmatrix, fsns=np.array(fsns))

    # Report table on sample stability
    tab = [['FSN', 'Date', 'Discrepancy', 'Relative discrepancy ((x-mean(x))/std(x))', 'Quality', 'Quality (cormap)']]
    badfsns = []
    badfsns_datcmp = []
    if cormaptest:
        matC, matp, matpadj, datcmp_ok = datcmp(*data1d)
    else:
        datcmp_ok = [not x for x in badidx]
    for h, bad, discr, dcmp_ok in zip(headers, badidx, rowavg, datcmp_ok):
        tab.append([h.fsn, h.date.isoformat(), discr, (discr - rowavgmean) / rowavgstd,
                    ["\u2713", "\u2718\u2718\u2718\u2718\u2718"][bad],
                    ["\u2713", "\u2718\u2718\u2718\u2718\u2718"][dcmp_ok != 1]])
        if bad:
            badfsns.append(h.fsn)
        if (not dcmp_ok and not np.isnan(dcmp_ok)):
            badfsns_datcmp.append(h.fsn)
    tab = ipy_table.IpyTable(tab)
    tab.apply_theme('basic')
    return badfsns, badfsns_datcmp, tab, rowavg
    def plot(self, axes):
        ''' Plot network on given axes
        '''

        classname = self.__class__.__name__
        fig = plt.gcf()
        divider = make_axes_locatable(axes)
        axes.axis([0,1,0,1])

        # Plot samples
        axes.scatter(self.samples[:,0], self.samples[:,1], s=1, color='g', alpha=0.5)
        C = self.adj
        Cx,Cy = C[...,0], C[...,1]

        if classname != 'SSk':
        
            for i in range(C.shape[0]):
                axes.plot (Cx[i,:], Cy[i,:], 'k', alpha=1, lw=1.5)
        
            for i in range(C.shape[1]):
                axes.plot (Cx[:,i], Cy[:,i], 'k', alpha=1, lw=1.5)
def plot_eigenvectors(ax, Y, idx, colormap):
    from matplotlib.ticker import MaxNLocator
    from mpl_toolkits.axes_grid import make_axes_locatable

    divider = make_axes_locatable(ax)
    ax2 = divider.new_vertical(size="100%", pad=0.05)
    fig1 = ax.get_figure()
    fig1.add_axes(ax2)
    ax2.set_title("Eigenvectors", fontsize=10)
    ax2.scatter(np.arange(0, len(Y)), Y[:, 0], s=10, c=idx, cmap=colormap, alpha=0.9, facecolors="none")
    ax2.axhline(0, ls="--", c="k")
    ax2.yaxis.set_major_locator(MaxNLocator(4))
    ax.yaxis.set_major_locator(MaxNLocator(4))
    ax.axhline(0, ls="--", c="k")
    ax.scatter(np.arange(0, len(Y)), Y[:, 1], s=10, c=idx, cmap=colormap, alpha=0.9, facecolors="none")
    ax.set_xlabel("index", fontsize=8)
    ax2.set_ylabel("2nd Smallest", fontsize=8)
    ax.set_ylabel("3nd Smallest", fontsize=8)
    change_tick_fontsize(ax, 8)
    change_tick_fontsize(ax2, 8)
    for tl in ax2.get_xticklabels():
        tl.set_visible(False)
def Scatter_hist(data1,
                 data2,
                 data1b=False,
                 data2b=False,
                 xbinwidth=0.5,
                 ybinwidth=0.5,
                 SSE=None,
                 SSEb=None,
                 vmax=1000.,
                 colormaps=cm.YlOrBr,
                 cleanstyle=False,
                 roodlichter=0.5,
                 *args,
                 **kwargs):
    '''
    Three-parts plot with the two parameter sitdirbutions plotted on the sides
    
    Parameters
    -----------
    data1: ndarray
        dataset 1 for x-axis
    data2: ndarray
        dataset 2 for y-axis
    data1b: ndarray
        dataset to plot along the data 1 set
    data2b: ndarray
        dataset to plot along the data 2 set
    binwidth: float
        defines the width of the bins relative to the data used
    cleanstyle: bool True|False
        if True, a more minimalistic version of the plot is given
    *args,  **kwargs: args
        arguments given toi the scatter plot
        example: s=15, marker='o', edgecolors= 'k',facecolor = 'white'

    Returns
    ---------
    fig: matplotlib.figure.Figure object
        the resulting figure
    axScatter: matplotlib.axes.AxesSubplot object
        the scatter plot with the datapoints, can be used to add labels or 
        change the current ticks settings
    axHistx: matplotlib.axes.AxesSubplot object
        the x-axis histogram
    axHisty: matplotlib.axes.AxesSubplot object
        the y-axis histogram
    
    Examples
    ----------
    >>> nMC = 1000
    >>> parval1 = np.random.gamma(5.5,size=nMC)   
    >>> parval2 = np.random.gamma(8.0,size=nMC)   
    >>> parnames = ['par1','par2']
    >>> fig,axScatter,axHistx,axHisty = Scatter_hist(parval1,parval2, 
                                                 cleanstyle = True, s=48, 
                                                 marker='o', edgecolors= 'k', 
                                                 facecolor = 'none',alpha=0.7)    
    >>> parval1b = np.random.uniform(low=0.0, high=30.0,size=nMC)   
    >>> parval2b = np.random.uniform(low=0.0, high=30.0,size=nMC)   
    >>> fig,axScatter,axHistx,axHisty = Scatter_hist(parval1,parval2,parval1b, 
                                                 parval2b, cleanstyle = True, 
                                                 s=48, marker='o', 
                                                 edgecolors= 'k', 
                                                 facecolor = 'none',
                                                 alpha=0.7)
    
    Notes
    ------
    Typical application is to check the dependency of two posterior 
    parameter distrbutions, eventually compared with their selected posteriors
    
    If a second dataset is added to compare, the style options of the scatter
    plot are fixed and the *args, **kwargs have no influence
    
    '''
    if not isinstance(data1, np.ndarray):
        raise Exception('dataset 1 need to be numpy ndarray')
    if not isinstance(data2, np.ndarray):
        raise Exception('dataset 2 need to be numpy ndarray')

    if isinstance(data1b, np.ndarray):
        if not isinstance(data2b, np.ndarray):
            raise Exception('Always combine the data of both')
    if isinstance(data2b, np.ndarray):
        if not isinstance(data1b, np.ndarray):
            raise Exception('Always combine the data of both')

    fig = plt.figure(figsize=(10, 10))
    axScatter = plt.subplot(111)
    divider = make_axes_locatable(axScatter)
    #axScatter.set_aspect('equal')
    axScatter.set_autoscale_on(True)

    # create a new axes with  above the axScatter
    axHistx = divider.new_vertical(1.5, pad=0.0001, sharex=axScatter)

    # create a new axes on the right side of the
    # axScatter
    axHisty = divider.new_horizontal(1.5, pad=0.0001, sharey=axScatter)

    fig.add_axes(axHistx)
    fig.add_axes(axHisty)

    # now determine nice limits by hand:
    #    binwidth = binwidth
    xmin = np.min(data1)
    xmax = np.max(data1)
    ymin = np.min(data2)
    ymax = np.max(data2)
    #xymax = np.max( [np.max(np.fabs(data1)), np.max(np.fabs(data2))] )
    #lim = (int(xymax/binwidth) + 1) * binwidth

    binsx = np.arange(xmin, xmax + xbinwidth, xbinwidth)
    binsy = np.arange(ymin, ymax + ybinwidth, ybinwidth)
    #bins = np.arange(-lim, lim + binwidth, binwidth)

    # the scatter plot:
    if isinstance(data1b, np.ndarray):  #TWO DATA ENTRIES
        if SSE == None:
            print '*args, **kwargs do not have any influcence when using two\
            options'

            axScatter.scatter(data1,
                              data2,
                              facecolor='none',
                              edgecolor='k',
                              s=25)
            axScatter.scatter(data1b,
                              data2b,
                              facecolor='none',
                              edgecolor='grey',
                              s=25)

            xminb = np.min(data1b)
            xmaxb = np.max(data1b)
            yminb = np.min(data2b)
            ymaxb = np.max(data2b)
            binsxb = np.arange(xminb, xmaxb + xbinwidth, xbinwidth)
            binsyb = np.arange(yminb, ymaxb + ybinwidth, ybinwidth)

            axHistx.hist(data1b,
                         bins=binsxb,
                         edgecolor='None',
                         color='grey',
                         normed=True)
            axHisty.hist(data2b,
                         bins=binsyb,
                         orientation='horizontal',
                         edgecolor='None',
                         color='grey',
                         normed=True)

            axHistx.hist(data1,
                         bins=binsx,
                         edgecolor='None',
                         color='k',
                         normed=True)
            axHisty.hist(data2,
                         bins=binsy,
                         orientation='horizontal',
                         edgecolor='None',
                         color='k',
                         normed=True)
        else:
            print '*args, **kwargs do not have any influcence when using two\
            options'

            sc1 = axScatter.scatter(data1b,
                                    data2b,
                                    c=SSEb,
                                    vmax=vmax,
                                    alpha=roodlichter,
                                    edgecolors='none',
                                    cmap=colormaps,
                                    *args,
                                    **kwargs)

            axScatter.scatter(data1,
                              data2,
                              c=SSE,
                              vmax=vmax,
                              edgecolors='none',
                              cmap=colormaps,
                              *args,
                              **kwargs)

            xminb = np.min(data1b)
            xmaxb = np.max(data1b)
            yminb = np.min(data2b)
            ymaxb = np.max(data2b)
            binsxb = np.arange(xminb, xmaxb + xbinwidth, xbinwidth)
            binsyb = np.arange(yminb, ymaxb + ybinwidth, ybinwidth)

            axHistx.hist(data1b,
                         bins=binsxb,
                         edgecolor='None',
                         color=colormaps(1.),
                         normed=True)
            axHisty.hist(data2b,
                         bins=binsyb,
                         orientation='horizontal',
                         color=colormaps(1.),
                         edgecolor='None',
                         normed=True)

            axHistx.hist(data1,
                         bins=binsx,
                         edgecolor='None',
                         color=colormaps(0.),
                         normed=True)
            axHisty.hist(data2,
                         bins=binsy,
                         orientation='horizontal',
                         edgecolor='None',
                         color=colormaps(0.),
                         normed=True)

    else:  #ONLY ONE DATA1 and DATA2
        if SSE == None:
            axScatter.scatter(data1, data2, c='black', *args, **kwargs)
            axHistx.hist(data1, bins=binsx, edgecolor='None', color='k')
            axHisty.hist(data2,
                         bins=binsy,
                         orientation='horizontal',
                         edgecolor='None',
                         color='k')
        else:
            axScatter.scatter(data1,
                              data2,
                              c=SSE,
                              vmax=vmax,
                              edgecolors='none',
                              cmap=colormaps,
                              *args,
                              **kwargs)
            axHistx.hist(data1, bins=binsx, edgecolor='None', color='k')
            axHisty.hist(data2,
                         bins=binsy,
                         orientation='horizontal',
                         edgecolor='None',
                         color='k')

    # the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
    # thus there is no need to manually adjust the xlim and ylim of these
    # axis.

    majloc1 = MaxNLocator(nbins=4, prune='lower')
    axScatter.yaxis.set_major_locator(majloc1)
    majloc2 = MaxNLocator(nbins=4)
    axScatter.xaxis.set_major_locator(majloc2)

    axScatter.grid(linestyle='dashed', color='0.75', linewidth=1.)
    axScatter.set_axisbelow(True)
    axHisty.set_axisbelow(True)
    axHistx.set_axisbelow(True)

    # The 'clean' environment
    if cleanstyle == True:
        plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
                 visible=False)
        plt.setp(axHistx.get_yticklabels() + axHisty.get_xticklabels(),
                 visible=False)
        axHisty.set_xticks([])
        axHistx.set_yticks([])
        axHistx.xaxis.set_ticks_position('bottom')
        axHisty.yaxis.set_ticks_position('left')

        axHisty.spines['right'].set_color('none')
        axHisty.spines['top'].set_color('none')
        axHisty.spines['bottom'].set_color('none')
        axHisty.spines['left'].set_color('none')

        axHistx.spines['top'].set_color('none')
        axHistx.spines['right'].set_color('none')
        axHistx.spines['left'].set_color('none')
        axHistx.spines['bottom'].set_color('none')
        axScatter.spines['top'].set_color('none')
        axScatter.spines['right'].set_color('none')
    else:
        plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
                 visible=False)
        for tl in axHisty.get_yticklabels():
            tl.set_visible(False)
        for tlp in axHisty.get_xticklabels():
            tlp.set_rotation(-90)

        majloc3 = MaxNLocator(nbins=4, prune='lower')
        axHistx.yaxis.set_major_locator(majloc3)
        axHistx.yaxis.tick_right()
        majloc4 = MaxNLocator(nbins=4, prune='lower')
        axHisty.xaxis.set_major_locator(majloc4)
        axHisty.xaxis.tick_top()

        axHisty.yaxis.grid(linestyle='dashed', color='0.75', linewidth=1.)
        axHistx.xaxis.grid(linestyle='dashed', color='0.75', linewidth=1.)

    return fig, axScatter, axHistx, axHisty, sc1
Exemple #12
0
    def show(self, location='right', width=0.2, pad=0.05, ticks=None,
             labels=True, log_format=False, box=None,
             box_orientation='vertical', axis_label_text=None,
             axis_label_rotation=None, axis_label_pad=5):
        '''
        Show a colorbar on the side of the image.

        Parameters
        ----------

        location : str, optional
            Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

        width : float, optional
            The width of the colorbar relative to the canvas size.

        pad : float, optional
            The spacing between the colorbar and the image relative to the
            canvas size.

        ticks : list, optional
            The position of the ticks on the colorbar.

        labels : bool, optional
            Whether to show numerical labels.

        log_format : bool, optional
            Whether to format ticks in exponential notation

        box : list, optional
            A custom box within which to place the colorbar. This should
            be in the form [xmin, ymin, dx, dy] and be in relative figure
            units. This overrides the location argument.

        box_orientation str, optional
            The orientation of the colorbar within the box. Can be
            'horizontal' or 'vertical'

        axis_label_text str, optional
            Optional text label of the colorbar.
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['log_format'] = log_format
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self._base_settings['axis_label_text'] = axis_label_text
        self._base_settings['axis_label_rotation'] = axis_label_rotation
        self._base_settings['axis_label_pad'] = axis_label_pad

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent.ax)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            if log_format:
                format = LogFormatterMathtext()
            else:
                format = None

            self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes,
                                                       orientation=orientation, format=format,
                                                       ticks=ticks)
            if axis_label_text:
                if axis_label_rotation:
                    self._colorbar.set_label(axis_label_text, rotation=axis_label_rotation)
                else:
                    self._colorbar.set_label(axis_label_text)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
                self._colorbar_axes.yaxis.set_label_position('right')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
                self._colorbar_axes.xaxis.set_label_position('top')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
                self._colorbar_axes.yaxis.set_label_position('left')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
                self._colorbar_axes.xaxis.set_label_position('bottom')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad

        else:

            warnings.warn("No image is shown, therefore, no colorbar will be plotted")
Exemple #13
0
def save_spa(odir, filename, stk, anlz, png, pdf, svg):
    
    SaveFileName = os.path.join(odir,filename)
    
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas  
    matplotlib.rcParams['pdf.fonttype'] = 42 
        
    colors=['#FF0000','#000000','#FFFFFF']
    spanclrmap=matplotlib.colors.LinearSegmentedColormap.from_list('spancm',colors)


    for i in range (anlz.n_target_spectra):
          
        #Save composition maps
        if anlz.pca_calculated == 0:
            tsmapimage = anlz.target_svd_maps[:,:,i]
        else:
            tsmapimage = anlz.target_pcafit_maps[:,:,i] 
    
        fig = matplotlib.figure.Figure(figsize =(PlotH, PlotH))
        canvas = FigureCanvas(fig)
        fig.clf()
        axes = fig.gca()
    
        divider = make_axes_locatable(axes)
        ax_cb = divider.new_horizontal(size="3%", pad=0.03)  
    
        fig.add_axes(ax_cb)
        axes.set_position([0.03,0.03,0.8,0.94])
    
    
        min_val = np.min(tsmapimage)
        max_val = np.max(tsmapimage)
        bound = np.max((np.abs(min_val), np.abs(max_val)))
              
    
        im = axes.imshow(tsmapimage, cmap=spanclrmap, vmin = -bound, vmax = bound)
        cbar = axes.figure.colorbar(im, orientation='vertical',cax=ax_cb)  
    
        axes.axis("off") 
            
        if png == 1:
            ext = 'png'               
            fileName_img = SaveFileName+"_TSmap_" +str(i+1)+"."+ext               
            fig.savefig(fileName_img, bbox_inches='tight', pad_inches = 0.0)    
        if pdf == 1:
            ext = 'pdf'               
            fileName_img = SaveFileName+"_TSmap_" +str(i+1)+"."+ext               
            fig.savefig(fileName_img, bbox_inches='tight', pad_inches = 0.0) 
        if svg == 1:
            ext = 'svg'               
            fileName_img = SaveFileName+"_TSmap_" +str(i+1)+"."+ext               
            fig.savefig(fileName_img, bbox_inches='tight', pad_inches = 0.0)     
            
            
            
    #Save spectra 
    for i in range (anlz.n_target_spectra):
        
        tspectrum = anlz.target_spectra[i, :]
                    
    
        fig = matplotlib.figure.Figure(figsize =(PlotW, PlotH))
        canvas = FigureCanvas(fig)
        fig.clf()
        fig.add_axes((0.15,0.15,0.75,0.75))
        axes = fig.gca()
    

        line1 = axes.plot(stk.ev,tspectrum, color='black', label = 'Raw data')
        
        if anlz.pca_calculated == 1: 
            tspectrumfit = anlz.target_pcafit_spectra[i, :]
            diff = np.abs(tspectrum-tspectrumfit)
            line2 = axes.plot(stk.ev,tspectrumfit, color='green', label = 'Fit')
            line3 = axes.plot(stk.ev,diff, color='grey', label = 'Abs(Raw-Fit)')
        
        fontP = matplotlib.font_manager.FontProperties()
        fontP.set_size('small')
   
        axes.legend(loc=4, prop = fontP)
                    
        axes.set_xlabel('Photon Energy [eV]')
        axes.set_ylabel('Optical Density')

        if png == 1:
            ext = 'png'   
            fileName_spec = SaveFileName+"_Tspectrum_" +str(i+1)+"."+ext
            fig.savefig(fileName_spec)    
        if pdf == 1:
            ext = 'pdf'   
            fileName_spec = SaveFileName+"_Tspectrum_" +str(i+1)+"."+ext
            fig.savefig(fileName_spec)
        if svg == 1:
            ext = 'svg'   
            fileName_spec = SaveFileName+"_Tspectrum_" +str(i+1)+"."+ext
            fig.savefig(fileName_spec)        

        fileName_spec = SaveFileName+"_Tspectrum_" +str(i+1)+".csv"
        cname = "Tspectrum_" +str(i+1)
        stk.write_csv(fileName_spec, stk.ev, tspectrum, cname = cname)
                
            
    return
Exemple #14
0
def makePlot(in_m, channel_names=None, fig=None, x_tick_rot=0, size=None, 
	     cmap=plt.cm.RdBu_r, colorbar=True, color_anchor=None, title=None, max_val=None, min_val=None):

	N = in_m.shape[0]
	ind = np.arange(N)  # the evenly spaced plot indices                                                    

	def channel_formatter(x, pos=None):
		thisind = np.clip(int(x), 0, N - 1)
		return channel_names[thisind]

	if fig is None:
		fig=plt.figure()

	if size is not None:
		fig.set_figwidth(size[0])
		fig.set_figheight(size[1])
	wid=fig.get_figwidth()
	ht=fig.get_figheight()
	ax_im = fig.add_subplot(1, 1, 1)

	#If you want to draw the colorbar:
	# what is make_axes_locatable?
        divider = make_axes_locatable(ax_im)
        ax_cb = divider.new_vertical(size="20%", pad=0.2, pack_start=True)
        fig.add_axes(ax_cb)

	#Make a copy of the input, so that you don't make changes to the original                               
	#data provided                                                                                          
	m = in_m.copy()

	
	#Null the upper triangle, so that you don't get the redundant and
	#the diagonal values:                                                                            
	#idx_null = triu_indices(m.shape[0])
	#m[idx_null] = np.nan

	#Extract the minimum and maximum values for scaling of the
	#colormap/colorbar:
	if max_val is None:
		max_val = np.nanmax(m)
		min_val = np.nanmin(m)

	if color_anchor is None:
		color_min = min_val
		color_max = max_val
	elif color_anchor == 0:
		bound = max(abs(max_val), abs(min_val))
		color_min = -bound
		color_max = bound
	else:
		color_min = color_anchor[0]
		color_max = color_anchor[1]

	#The call to imshow produces the matrix plot:
	im = ax_im.imshow(m, origin='upper', interpolation='nearest',
	vmin=color_min, vmax=color_max, cmap=cmap)

	#Formatting:
	ax = ax_im
	ax.grid(True)
	#Label each of the cells with the row and the column:
	if channel_names is not None:
		for i in xrange(0, m.shape[0]):
			if i < (m.shape[0] - 1):
				ax.text(i - 0.3, i, channel_names[i], rotation=x_tick_rot)
			if i > 0:
				ax.text(-1, i + 0.3, channel_names[i], horizontalalignment='right')

        ax.set_axis_off()
        ax.set_xticks(np.arange(N))
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(channel_formatter))
        fig.autofmt_xdate(rotation=x_tick_rot)
        ax.set_yticks(np.arange(N))
        ax.set_yticklabels(channel_names)
        ax.set_ybound([-0.5, N - 0.5])
        ax.set_xbound([-0.5, N - 1.5])

	#Make the tick-marks invisible:                                                                         
	for line in ax.xaxis.get_ticklines():
		line.set_markeredgewidth(0)

	for line in ax.yaxis.get_ticklines():
		line.set_markeredgewidth(0)

	ax.set_axis_off()

	if title is not None:
		ax.set_title(title)

	#The following produces the colorbar and sets the ticks                                                 
	if colorbar:
        #Set the ticks - if 0 is in the interval of values, set that, as well                               
        #as the maximal and minimal values:                                                                 
		if min_val < 0:
			ticks = [min_val, 0, max_val]
		#Otherwise - only set the minimal and maximal value:                                                
		else:
			ticks = [min_val, max_val]

        #This makes the colorbar:                                                                           
        cb = fig.colorbar(im, cax=ax_cb, orientation='horizontal',
                          cmap=cmap,
                          norm=im.norm,
                          boundaries=np.linspace(min_val, max_val, 256),
                          ticks=ticks,
                          format='%.2f')

   
	# Set the current figure active axis to be the top-one, which is the one                                
	# most likely to be operated on by users later on                                                       
	fig.sca(ax)

	return fig
Exemple #15
0
def draw_graph(G,
               labels=None,
               node_colors=None,
               node_shapes=None,
               node_scale=1.0,
               edge_style='solid',
               edge_cmap=None,
               colorbar=False,
               vrange=None,
               layout=None,
               title=None,
               font_family='sans-serif',
               font_size=9,
               stretch_factor=1.0,
               edge_alpha=True,
               fig_size=None):
    """Draw a weighted graph with options to visualize link weights.

    The resulting diagram uses the rank of each node as its size, and the
    weight of each link (after discarding thresholded values, see below) as the
    link opacity.

    It maps edge weight to color as well as line opacity and thickness,
    allowing the color part to be hardcoded over a value range (to permit valid
    cross-figure comparisons for different graphs, so the same color
    corresponds to the same link weight even if each graph has a different
    range of weights).  The nodes sizes are proportional to their degree,
    computed as the sum of the weights of all their links.  The layout defaults
    to circular, but any nx layout function can be passed in, as well as a
    statically precomputed layout.

    Parameters
    ----------
    G : weighted graph
      The values must be of the form (v1,v2), with all v2 in [0,1].  v1 are
      used for colors, v2 for thickness/opacity.

    labels : list or dict, optional.
      An indexable object that maps nodes to strings.  If not given, the
      string form of each node is used as a label.  If False, no labels are
      drawn.

    node_colors : list or dict, optional.
      An indexable object that maps nodes to valid matplotlib color specs.  See
      matplotlib's plot() function for details.

    node_shapes : list or dict, optional.
      An indexable object that maps nodes to valid matplotlib shape specs.  See
      matplotlib's scatter() function for details.  If not given, circles are
      used.

    node_scale : float, optional
      A scale factor to globally stretch or shrink all nodes symbols by.

    edge_style : string, optional
      Line style for the edges, defaults to 'solid'.

    edge_cmap : matplotlib colormap, optional.
      A callable that returns valid color specs, like matplotlib colormaps.
      If not given, edges are colored black.

    colorbar : bool
      If true, automatically add a colorbar showing the mapping of graph weight
      values to colors.

    vrange : pair of floats
      If given, this indicates the total range of values that the weights can
      in principle occupy, and is used to set the lower/upper range of the
      colormap.  This allows you to set the range of multiple different figures
      to the same values, even if each individual graph has range variations,
      so that visual color comparisons across figures are valid.

    layout : function or layout dict, optional
      A NetworkX-like layout function or the result of a precomputed layout for
      the given graph.  NetworkX produces layouts as dicts keyed by nodes and
      with (x,y) pairs of coordinates as values, any function that produces
      this kind of output is acceptable.  Defaults to nx.circular_layout.

    title : string, optional.
      If given, title to put on the main plot.

    font_family : string, optional.
      Font family used for the node labels and title.

    font_size : int, optional.
      Font size used for the node labels and title.

    stretch_factor : float, optional
      A global scaling factor to make the graph larger (or smaller if <1).
      This can be used to separate the nodes if they start overlapping.

    edge_alpha: bool, optional
      Whether to weight the transparency of each edge by a factor equivalent to
      its relative weight

    fig_size: list of height by width, the size of the figure (in
    inches). Defaults to [6,6]

    Returns
    -------
    fig
      The matplotlib figure object with the plot.
    """
    if fig_size is None:
        figsize = [6, 6]

    scaler = figsize[0] / 6.
    # For the size of the node symbols
    node_size_base = 1000 * scaler
    node_min_size = 200 * scaler
    default_node_shape = 'o'
    # Default colors if none given
    default_node_color = 'r'
    default_edge_color = 'k'
    # Max edge width
    max_width = 13 * scaler
    min_width = 2 * scaler
    font_family = 'sans-serif'

    # We'll use the nodes a lot, let's make a numpy array of them
    nodes = np.array(sorted(G.nodes()))
    nnod = len(nodes)

    # Build a 'weighted degree' array obtained by adding the (absolute value)
    # of the weights for all edges pointing to each node:
    amat = nx.adj_matrix(G).A  # get a normal array out of it
    degarr = abs(amat).sum(0)  # weights are sums across rows

    # Map the degree to the 0-1 range so we can use it for sizing the nodes.
    try:
        odegree = rescale_arr(degarr, 0, 1)
        # Make an array of node sizes based on node degree
        node_sizes = odegree * node_size_base + node_min_size
    except ZeroDivisionError:
        # All nodes same size
        node_sizes = np.empty(nnod, float)
        node_sizes.fill(0.5 * node_size_base + node_min_size)

    # Adjust node size list.  We square the scale factor because in mpl, node
    # sizes represent area, not linear size, but it's more intuitive for the
    # user to think of linear factors (the overall figure scale factor is also
    # linear).
    node_sizes *= node_scale ** 2

    # Set default node properties
    if node_colors is None:
        node_colors = [default_node_color] * nnod

    if node_shapes is None:
        node_shapes = [default_node_shape] * nnod

    # Set default edge colormap
    if edge_cmap is None:
        # Make an object with the colormap API, that maps all input values to
        # the default color (with proper alhpa)
        edge_cmap = (lambda val, alpha:
                     colors.colorConverter.to_rgba(default_edge_color, alpha))

    # if vrange is None, we set the color range from the values, else the user
    # can specify it

    # e[2] is edge value: edges_iter returns (i,j,data)
    gvals = np.array([e[2]['weight'] for e in G.edges(data=True)])
    gvmin, gvmax = gvals.min(), gvals.max()

    gvrange = gvmax - gvmin
    if vrange is None:
        vrange = gvmin, gvmax
    # Now, construct the normalization for the colormap
    cnorm = mpl.colors.Normalize(vmin=vrange[0], vmax=vrange[1])

    # Create the actual plot where the graph will be displayed
    figsize = np.array(figsize, float)
    figsize *= stretch_factor

    fig = plt.figure(figsize=figsize)
    ax_graph = fig.add_subplot(1, 1, 1)
    fig.sca(ax_graph)

    if layout is None:
        layout = nx.circular_layout
    # Compute positions for all nodes - nx has several algorithms
    if callable(layout):
        pos = layout(G)
    else:
        # The user can also provide a precomputed layout
        pos = layout

    # Draw nodes
    for nod in nodes:
        nx.draw_networkx_nodes(G,
                               pos,
                               nodelist=[nod],
                               node_color=node_colors[nod],
                               node_shape=node_shapes[nod],
                               node_size=node_sizes[nod])
    # Draw edges
    if not isinstance(G, nx.DiGraph):
        # Undirected graph, simple lines for edges
        # We need the size of the value range to properly scale colors
        vsize = vrange[1] - vrange[0]
        gvals_normalized = G.metadata['vals_norm']
        for (u, v, y) in G.edges(data=True):
            # The graph value is the weight, and the normalized values are in
            # [0,1], used for thickness/transparency
            alpha = gvals_normalized[u, v]
            # Scale the color choice to the specified vrange, so that
            ecol = (y['weight'] - vrange[0]) / vsize
            #print 'u,v:',u,v,'y:',y,'ecol:',ecol  # dbg

            if edge_alpha:
                fade = alpha
            else:
                fade = 1.0

            edge_color = [tuple(edge_cmap(ecol, fade))]
            #dbg:
            #print u,v,y
            draw_networkx_edges(G,
                                pos,
                                edgelist=[(u, v)],
                                width=min_width + alpha * max_width,
                                edge_color=edge_color,
                                style=edge_style)
    else:
        # Directed graph, use arrows.
        # XXX - this is currently broken.
        raise NotImplementedError("arrow drawing currently broken")

        ## for (u,v,x) in G.edges(data=True):
        ##     y,w = x
        ##     draw_arrows(G,pos,edgelist=[(u,v)],
        ##                 edge_color=[w],
        ##                 alpha=w,
        ##                 edge_cmap=edge_cmap,
        ##                 width=w*max_width)

    # Draw labels.  If not given, we use the string form of the nodes.  If
    # labels is False, no labels are drawn.
    if labels is None:
        labels = map(str, nodes)

    if labels:
        lab_idx = range(len(labels))
        labels_dict = dict(zip(lab_idx, labels))
        nx.draw_networkx_labels(G,
                                pos,
                                labels_dict,
                                font_size=font_size,
                                font_family=font_family)

    if title:
        plt.title(title, fontsize=font_size)

    # Turn off x and y axes labels in pylab
    plt.xticks([])
    plt.yticks([])

    # Add a colorbar if requested
    if colorbar:
        divider = make_axes_locatable(ax_graph)
        ax_cb = divider.new_vertical(size="20%", pad=0.2, pack_start=True)
        fig.add_axes(ax_cb)
        cb = mpl.colorbar.ColorbarBase(ax_cb,
                                    cmap=edge_cmap,
                                    norm=cnorm,
                                    #boundaries = np.linspace(min((gvmin,0)),
                                    #                         max((gvmax,0)),
                                    #                         256),
                                    orientation='horizontal',
                                    format='%.2f')

    # Always return the MPL figure object so the user can further manipulate it
    return fig
Exemple #16
0
def plot_tri_matrix(mat,
                    figure=None,
                    num='plot_part_of_this_matrix',
                    size=None,
                    cmap=pyplot.cm.RdBu_r,
                    colourbar=True,
                    color_anchor=None,
                    node_labels=None,
                    x_tick_rot=0,
                    title=None):
    r"""Creates a lower-triangle of a square matrix. Very often found to display correlations or coherence.

    Parameters
    ----------

    mat          : square matrix

    node_labels  : list of strings with the labels to be applied to 
                   the nodes. Defaults to '0','1','2', etc.

    fig          : a matplotlib figure

    cmap         : a matplotlib colormap.

    title        : figure title (eg '$\alpha$')

    color_anchor : determines the clipping for the colormap. 
                   If None, the data min, max are used.
                   If 0, min and max of colormap correspond to max abs(mat)
                   If (a,b), min and max are set accordingly (a,b)

    Returns
    -------

    fig: a figure object

    """
    def channel_formatter(x, pos=None):
        thisidx = numpy.clip(int(x), 0, N - 1)
        return node_labels[thisidx]

    if figure is not None:
        fig = figure
    else:
        if num is None:
            fig = pyplot.figure()
        else:
            fig = pyplot.figure(num=num)

    if size is not None:
        fig.set_figwidth(size[0])
        fig.set_figheight(size[1])

    w = fig.get_figwidth()
    h = fig.get_figheight()

    ax_im = fig.add_subplot(1, 1, 1)

    N = mat.shape[0]
    idx = numpy.arange(N)

    if colourbar:
        if IMPORTED_MPL_TOOLKITS:
            divider = make_axes_locatable(ax_im)
            ax_cb = divider.new_vertical(size="10%", pad=0.1, pack_start=True)
            fig.add_axes(ax_cb)
        else:
            pass

    mat_copy = mat.copy()

    #Null the upper triangle, including the main diagonal.
    idx_null = numpy.triu_indices(mat_copy.shape[0])
    mat_copy[idx_null] = numpy.nan

    #Min max values
    max_val = numpy.nanmax(mat_copy)
    min_val = numpy.nanmin(mat_copy)

    if color_anchor is None:
        color_min = min_val
        color_max = max_val
    elif color_anchor == 0:
        bound = max(abs(max_val), abs(min_val))
        color_min = -bound
        color_max = bound
    else:
        color_min = color_anchor[0]
        color_max = color_anchor[1]

    #The call to imshow produces the matrix plot:
    im = ax_im.imshow(mat_copy,
                      origin='upper',
                      interpolation='nearest',
                      vmin=color_min,
                      vmax=color_max,
                      cmap=cmap)

    #Formatting:
    ax = ax_im
    ax.grid(True)
    #Label each of the cells with the row and the column:
    if node_labels is not None:
        for i in range(0, mat_copy.shape[0]):
            if i < (mat_copy.shape[0] - 1):
                ax.text(i - 0.3, i, node_labels[i], rotation=x_tick_rot)
            if i > 0:
                ax.text(-1,
                        i + 0.3,
                        node_labels[i],
                        horizontalalignment='right')

        ax.set_axis_off()
        ax.set_xticks(numpy.arange(N))
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(channel_formatter))
        fig.autofmt_xdate(rotation=x_tick_rot)
        ax.set_yticks(numpy.arange(N))
        ax.set_yticklabels(node_labels)
        ax.set_ybound([-0.5, N - 0.5])
        ax.set_xbound([-0.5, N - 1.5])

    #Make the tick-marks invisible:
    for line in ax.xaxis.get_ticklines():
        line.set_markeredgewidth(0)

    for line in ax.yaxis.get_ticklines():
        line.set_markeredgewidth(0)

    ax.set_axis_off()

    if title is not None:
        ax.set_title(title)

    if colourbar:
        #Set the ticks - if 0 is in the interval of values, set that, as well
        #as the min, max values:
        if min_val < 0:
            ticks = [color_min, min_val, 0, max_val, color_max]
        #set the min, mid and  max values:
        else:
            ticks = [
                color_min, min_val, (color_max - color_min) / 2., max_val,
                color_max
            ]

        #colourbar:
        if IMPORTED_MPL_TOOLKITS:
            cb = fig.colorbar(im,
                              cax=ax_cb,
                              orientation='horizontal',
                              cmap=cmap,
                              norm=im.norm,
                              boundaries=numpy.linspace(
                                  color_min, color_max, 256),
                              ticks=ticks,
                              format='%.2f')

        else:
            # the colourbar will be wider than the matrix
            cb = fig.colorbar(im,
                              orientation='horizontal',
                              cmap=cmap,
                              norm=im.norm,
                              boundaries=numpy.linspace(
                                  color_min, color_max, 256),
                              ticks=ticks,
                              format='%.2f')

    fig.sca(ax)

    return fig
Exemple #17
0
    def show(self,
             location='right',
             width=0.2,
             pad=0.05,
             ticks=None,
             labels=True,
             box=None,
             box_orientation='vertical'):
        '''
        Show a colorbar on the side of the image.

        Optional Keyword Arguments:

            *location*: [ string ]
                Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

            *width*: [ float ]
                The width of the colorbar relative to the canvas size.

            *pad*: [ float ]
                The spacing between the colorbar and the image relative to the canvas size.

            *ticks*: [ None or list ]
                The position of the ticks on the colorbar.

            *labels*: [ True or False ]
                Whether to show numerical labels.

            *box*: [ list ]
                A custom box within which to place the colorbar. This should
                be in the form [xmin, ymin, dx, dy] and be in relative figure
                units. This overrides the location argument.

            *box_orientation* [ str ]
                The orientation of the colorbar within the box. Can be
                'horizontal' or 'vertical'
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent._ax1)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(
                        size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(
                        size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(
                        size=width,
                        pad=pad,
                        pack_start=True,
                        axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(
                        size=width,
                        pad=pad,
                        pack_start=True,
                        axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            self._colorbar = self._parent._figure.colorbar(
                self._parent.image,
                cax=self._colorbar_axes,
                orientation=orientation,
                ticks=ticks)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False

        else:

            warnings.warn(
                "No image is shown, therefore, no colorbar will be plotted")
Exemple #18
0
def map_spatial_analog(ncfile, variable='dissimilarity', cmap='viridis', title='Spatial analog'):
    """Return a matplotlib Figure instance showing a map of the dissimilarity measure.
    """
    import netCDF4 as nc
    from flyingpigeon import utils
    from mpl_toolkits.axes_grid import make_axes_locatable
    import matplotlib.axes as maxes

    try:
        var = utils.get_values(ncfile, variable)
        LOGGER.info('Data loaded')

        lats, lons = utils.get_coordinates(ncfile, variable=variable, unrotate=False)

        if len(lats.shape) == 1:
            cyclic_var, cyclic_lons = add_cyclic_point(var, coord=lons)

            lons = cyclic_lons.data
            var = cyclic_var

        with nc.Dataset(ncfile) as D:
            V = D.variables[variable]
            lon, lat = map(float, V.target_location.split(','))

        LOGGER.info('Lat and lon loaded')

    except Exception as e:
        msg = 'Failed to get data for plotting: {0}\n{1}'.format(ncfile, e)
        LOGGER.exception(msg)
        raise Exception(msg)

    try:
        fig = plt.figure(facecolor='w', edgecolor='k')
        fig.subplots_adjust(top=.95, bottom=.05, left=.03, right=.95)

        ax = plt.axes(
            projection=ccrs.Robinson(central_longitude=int(np.mean(lons))))

        divider = make_axes_locatable(ax)
        cax = divider.new_horizontal("4%", pad=0.15, axes_class=maxes.Axes)
        fig.add_axes(cax)

        ax.plot(lon, lat, marker='o', mfc='#292421', ms=13, transform=ccrs.PlateCarree())
        ax.plot(lon, lat, marker='o', mfc='#ffffff', ms=7, transform=ccrs.PlateCarree())

        cs = ax.contourf(lons, lats, var, 60,
                         transform=ccrs.PlateCarree(),
                         cmap=cmap, interpolation='nearest')

        ax.coastlines(color='k', linewidth=.8)
        ax.set_title(title)

        cb = plt.colorbar(cs, cax=cax, orientation='vertical')
        cb.set_label(u"–            Dissimilarity             +")  # ha='left', va='center')
        cb.set_ticks([])

    except:
        msg = 'failed to plot graphic'
        LOGGER.exception(msg)

    LOGGER.info('Plot created and figure saved')
    return fig
Exemple #19
0
from mpl_toolkits.axes_grid import make_axes_locatable
import matplotlib.axes as maxes
from matplotlib import cm

if __name__ == '__main__':

    fig = P.figure(figsize=(10, 10))
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(224)

    s1 = ax1.scatter(numpy.random.rand(10),
                     numpy.random.rand(10),
                     c=numpy.random.rand(10))
    divider = make_axes_locatable(ax1)
    cax1 = divider.new_horizontal('5%', pad=0.0, axes_class=maxes.Axes)
    fig.add_axes(cax1)
    c1 = fig.colorbar(s1, cax=cax1, orientation='horizontal')

    s2 = ax2.scatter(numpy.random.rand(10),
                     numpy.random.rand(10),
                     c=numpy.random.rand(10),
                     cmap=cm.get_cmap('jet'))
    divider = make_axes_locatable(ax2)
    cax2 = divider.append_axes('right', 0.1, pad=0.1)
    c2 = fig.colorbar(s2, cax=cax2)
    #p =  matplotlib.patches.Patch(color=cm.get_cmap('jet'))
    #ax2.legend([p],['Test'])

    s3 = ax3.scatter(numpy.random.rand(10),
Exemple #20
0
of.close()
f.close()

data = np.loadtxt(ofName)
os.unlink(ofName)

x = data[:, xcol - 1]
y = data[:, ycol - 1]

fig = plt.figure(1, figsize=(8.5, 8.5))

from mpl_toolkits.axes_grid import make_axes_locatable

axScatter = plt.subplot(111)
divider = make_axes_locatable(axScatter)

# create a new axes with a height of 1.2 inch above the axScatter
axHistx = divider.new_vertical(1.2, pad=0.1, sharex=axScatter)

# create a new axes with a width of 1.2 inch on the right side of the
# axScatter
axHisty = divider.new_horizontal(1.2, pad=0.1, sharey=axScatter)

fig.add_axes(axHistx)
fig.add_axes(axHisty)

# make some labels invisible
plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(), visible=False)

# the scatter plot:
Exemple #21
0
    def plot(self, axes):
        ''' Plot network on given axes

         :Parameters:
         `axes` : matploltlib Axes
             axes where to draw network
        '''

        classname = self.__class__.__name__

        # Plot samples
        axes.scatter(self.samples[:,0], self.samples[:,1], s=1.0, color='b', alpha=0.25)

        fig = plt.gcf()
        divider = make_axes_locatable(axes)

        # Plot network
        C = self.codebook
        Cx,Cy = C[...,0], C[...,1]
        if classname != 'NG':
            for i in range(C.shape[0]):
                axes.plot (Cx[i,:], Cy[i,:], 'k', alpha=0.85, lw=1.5)
            for i in range(C.shape[1]):
                axes.plot (Cx[:,i], Cy[:,i], 'k', alpha=0.85, lw=1.5)
        axes.scatter (Cx.flatten(), Cy.flatten(), s=50, c= 'w', edgecolors='k', zorder=10)
        axes.axis([0,1,0,1])
        axes.set_xticks([])
        axes.set_yticks([])
        axes.set_aspect(1)

        # Plot distortion
        subaxes = divider.new_vertical(1.0, pad=0.4, sharex=axes)
        fig.add_axes(subaxes)
        subaxes.set_xticks([])
        subaxes.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
        subaxes.yaxis.set_ticks_position('right')
        subaxes.set_ylabel('Distortion')
        subaxes.set_xlabel('Time')
        #subaxes.axis([0,1,0,1])
        Y = self.distortion[::1]
        X = np.arange(len(Y))/float(len(Y)-1)
        subaxes.plot(X,Y)
        axes.axis([0,1,0,1])

        if classname == 'NG':
            plt.title('Neural Gas', fontsize=20)
        elif classname == 'SOM':
            plt.title('Self-Organizing Map', fontsize=20)
        elif classname == 'DSOM':
            plt.title('Dynamic Self-Organizing Map', fontsize=20)
        if classname == 'NG':
            axes.text(0.5, -0.01,
                      r'$\lambda_i = %.3f,\lambda_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                    self.sigma_i, self.sigma_f, self.lrate_i, self.lrate_f),
                      fontsize=16, 
                      horizontalalignment='center',
                      verticalalignment='top',
                      transform = axes.transAxes)
        if classname == 'SOM':
            axes.text(0.5, -0.01,
                      r'$\sigma_i = %.3f,\sigma_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                    self.sigma_i, self.sigma_f, self.lrate_i, self.lrate_f),
                      fontsize=16, 
                      horizontalalignment='center',
                      verticalalignment='top',
                      transform = axes.transAxes)
        elif classname == 'DSOM':
            axes.text(0.5, -0.01,
                      r'$elasticity = %.2f$, $\varepsilon = %.3f$' % (self.elasticity, self.lrate),
                      fontsize=16, 
                      horizontalalignment='center',
                      verticalalignment='top',
                      transform = axes.transAxes)
Exemple #22
0
    def plot(self, statsResults):
        '''
    Create extended error bar plot.
      filename: name of output file
      data: matrix of data for each feature of interest; [feature, pValue, effectSize, lowerCI, upperCI, seq1, seq1, power]
      oneMinusAlpha: 1-alpha value used to create above data matrix
    '''

        # *** Check if there is sufficient data to generate the plot
        if len(statsResults.activeData) <= 0:
            self.emptyAxis()
            return

        features = statsResults.getColumn('Features')
        if len(features) > 200:
            QtGui.QApplication.instance().setOverrideCursor(
                QtGui.QCursor(QtCore.Qt.ArrowCursor))
            reply = QtGui.QMessageBox.question(
                self, 'Continue?',
                'Profile contains ' + str(len(features)) + ' features. ' +
                'It may take several seconds to generate this plot. We recommend filtering your profile first. '
                + 'Do you wish to continue?', QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No)
            QtGui.QApplication.instance().restoreOverrideCursor()
            if reply == QtGui.QMessageBox.No:
                self.emptyAxis()
                return

        # *** Colour of plot elements
        profile1Colour = str(self.preferences['Sample 1 colour'].name())
        profile2Colour = str(self.preferences['Sample 2 colour'].name())

        # *** Colour of plot elements
        highlightColor = (0.9, 0.9, 0.9)
        orangeColour = (1, 0.5, 0)

        # *** Sort data
        if self.sortingField == 'p-values':
            statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\
                                                              [statsResults.dataHeadings['pValues']], False)
        elif self.sortingField == 'Effect sizes':
            statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\
                                                              [statsResults.dataHeadings['EffectSize']],
                                                              True, True, statsResults.confIntervMethod.bRatio)

        elif self.sortingField == 'Feature labels':
            statsResults.activeData = TableHelper.SortTableStrCol(statsResults.activeData,\
                                                              statsResults.dataHeadings['Features'], False)

        # *** Create lists for each quantity of interest
        features = statsResults.getColumn('Features')

        if statsResults.multCompCorrection.method == 'False discovery rate':
            pValueTitle = 'q-value'
        else:
            pValueTitle = 'p-value'

        if self.bShowCorrectedPvalues:
            pValueLabels = statsResults.getColumnAsStr('pValuesCorrected')
            pValueTitle += ' (corrected)'
        else:
            pValueLabels = statsResults.getColumnAsStr('pValues')

        effectSizes = statsResults.getColumn('EffectSize')

        lowerCIs = statsResults.getColumn('LowerCI')
        upperCIs = statsResults.getColumn('UpperCI')
        ciTitle = (
            '%.3g' %
            (statsResults.oneMinusAlpha() * 100)) + '% confidence intervals'

        seqs1 = statsResults.getColumn('Seq1')
        seqs2 = statsResults.getColumn('Seq2')
        power = statsResults.getColumn('Power')

        # *** Truncate feature labels
        selectedFeatures = list(
            self.preferences['Selected statistical features'])
        if self.preferences['Truncate feature names']:
            length = self.preferences['Length of truncated feature names']

            for i in xrange(0, len(features)):
                if len(features[i]) > length + 3:
                    features[i] = features[i][0:length] + '...'

            for i in xrange(0, len(selectedFeatures)):
                if len(selectedFeatures[i]) > length + 3:
                    selectedFeatures[i] = selectedFeatures[i][0:length] + '...'

        # *** Check that there is at least one significant feature
        if len(features) <= 0:
            self.emptyAxis('No significant features')
            return

        # *** Adjust effect size for axis scale
        dominateInSample2 = []
        for i in xrange(0, len(effectSizes)):
            seqs1[i] = -seqs1[i]

            if statsResults.confIntervMethod.bRatio:
                if effectSizes[i] < 1:
                    # mirror CI across y-axis
                    effectSizes[i] = 1.0 / effectSizes[i]
                    lowerCI = effectSizes[i] - (1.0 / upperCIs[i])
                    upperCI = (1.0 / lowerCIs[i]) - effectSizes[i]

                    lowerCIs[i] = lowerCI
                    upperCIs[i] = upperCI

                    dominateInSample2.append(i)
                else:
                    lowerCIs[i] = effectSizes[i] - lowerCIs[i]
                    upperCIs[i] = upperCIs[i] - effectSizes[i]
            else:
                lowerCIs[i] = effectSizes[i] - lowerCIs[i]
                upperCIs[i] = upperCIs[i] - effectSizes[i]
                if effectSizes[i] < 0.0:
                    dominateInSample2.append(i)

        # *** Determine which axes should be created
        bShowPowerPlot = self.bShowPowerPlot and len(
            power) != 0 and not math.isnan(power[0])

        # *** Set figure size
        plotHeight = self.figHeightPerRow * len(features)
        self.imageWidth = self.figWidth
        self.imageHeight = plotHeight + 0.65  # 0.65 inches for bottom and top labels
        if self.imageWidth > 256 or self.imageHeight > 256:
            QtGui.QApplication.instance().setOverrideCursor(
                QtGui.QCursor(QtCore.Qt.ArrowCursor))
            self.emptyAxis()
            reply = QtGui.QMessageBox.question(
                self, 'Excessively large plot',
                'The resulting plot is too large to display.')
            QtGui.QApplication.instance().restoreOverrideCursor()
            return

        self.fig.set_size_inches(self.imageWidth, self.imageHeight)

        # *** Determine width of y-axis labels
        yLabelBounds = self.yLabelExtents(features, 8)

        # *** Size plots which comprise the extended errorbar plot
        self.fig.clear()

        spacingBetweenPlots = 0.3  # inches
        heightBottomLabels = 0.4  # inches
        totalSpacingBetweenPlots = spacingBetweenPlots * 2  # inches

        widthNumSeqPlot = 1.25  # inches
        if self.bShowSeqPlot == False:
            widthNumSeqPlot = 0.0
            totalSpacingBetweenPlots -= spacingBetweenPlots

        widthPowerPlot = 0.75  # inches
        if bShowPowerPlot == False:
            widthPowerPlot = 0.0
            totalSpacingBetweenPlots -= spacingBetweenPlots

        widthPvalueLabels = 0.75  # inches
        if self.bShowPValueLabels == False:
            widthPvalueLabels = 0.1

        yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight
        heightPlotFigSpace = plotHeight / self.imageHeight

        xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth
        pValueLabelWidthFigSpace = widthPvalueLabels / self.imageWidth
        widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace

        widthErrorBarPlot = widthPlotFigSpace * self.imageWidth - widthNumSeqPlot - widthPowerPlot - totalSpacingBetweenPlots

        axInitAxis = self.fig.add_axes([
            xPlotOffsetFigSpace, yPlotOffsetFigSpace, widthPlotFigSpace,
            heightPlotFigSpace
        ])
        divider = make_axes_locatable(axInitAxis)
        divider.get_vertical()[0] = Size.Fixed(
            len(features) * self.figHeightPerRow)

        if self.bShowSeqPlot == True:
            divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot)
            axErrorbar = divider.new_horizontal(widthErrorBarPlot,
                                                pad=spacingBetweenPlots,
                                                sharey=axInitAxis)
            self.fig.add_axes(axErrorbar)
        else:
            divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot)
            axErrorbar = axInitAxis

        if bShowPowerPlot == True:
            axPower = divider.new_horizontal(widthPowerPlot,
                                             pad=spacingBetweenPlots,
                                             sharey=axInitAxis)
            self.fig.add_axes(axPower)

        # *** Plot of sequences for each subsystem
        if self.bShowSeqPlot == True:
            axNumSeq = axInitAxis

            axNumSeq.hlines(np.arange(len(features)), [0],
                            seqs1,
                            lw=4,
                            color=profile1Colour,
                            zorder=10)
            axNumSeq.hlines(np.arange(len(features)), [0],
                            seqs2,
                            lw=4,
                            color=profile2Colour,
                            zorder=10)
            for value in np.arange(-0.5, len(features) - 1, 2):
                axNumSeq.axhspan(value,
                                 value + 1,
                                 facecolor=highlightColor,
                                 edgecolor='none',
                                 zorder=1)

            axNumSeq.vlines(0, -1, len(features), color='black', zorder=10)

            axNumSeq.set_xlabel(self.xLabel, fontsize=8)
            axNumSeq.set_xticks([min(seqs1), 0, max(seqs2)])
            axNumSeq.set_xticklabels([-min(seqs1), 0, max(seqs2)])

            axNumSeq.set_yticks(np.arange(len(features)))
            axNumSeq.set_yticklabels(features, size=8)
            axNumSeq.set_ylim([-1, len(features)])

            for label in axNumSeq.get_xticklabels():
                label.set_size(8)

            for label in axNumSeq.get_yticklabels():
                label.set_size(8)
                if label.get_text() in selectedFeatures:
                    label.set_color('red')

            for a in axNumSeq.yaxis.majorTicks:
                a.tick1On = False
                a.tick2On = False

            for a in axNumSeq.xaxis.majorTicks:
                a.tick1On = True
                a.tick2On = False

            for loc, spine in axNumSeq.spines.iteritems():
                if loc in ['left', 'right', 'top']:
                    spine.set_color('none')

        # *** Plot confidence intervals for each subsystem
        lastAxes = axErrorbar
        axErrorbar.errorbar(effectSizes,
                            np.arange(len(features)),
                            xerr=[lowerCIs, upperCIs],
                            fmt='o',
                            mfc=profile1Colour,
                            mec='black',
                            ecolor='black',
                            zorder=10)
        effectSizesSample2 = [
            effectSizes[value] for value in dominateInSample2
        ]
        axErrorbar.plot(effectSizesSample2,
                        dominateInSample2,
                        ls='',
                        marker='o',
                        mfc=profile2Colour,
                        mec='black',
                        zorder=100)

        if statsResults.confIntervMethod.bRatio:
            axErrorbar.vlines(1,
                              -1,
                              len(features),
                              linestyle='dashed',
                              color=(0.25, 0.25, 0.25))
        else:
            axErrorbar.vlines(0,
                              -1,
                              len(features),
                              linestyle='dashed',
                              color=(0.25, 0.25, 0.25))

        for value in np.arange(-0.5, len(features) - 1, 2):
            axErrorbar.axhspan(value,
                               value + 1,
                               facecolor=highlightColor,
                               edgecolor='none',
                               zorder=1)

        axErrorbar.set_title(ciTitle, fontsize=8)
        axErrorbar.set_xlabel(statsResults.confIntervMethod.plotLabel,
                              fontsize=8)

        if self.bCustomLimits:
            axErrorbar.set_xlim([self.minX, self.maxX])
        else:
            self.minX, self.maxX = axErrorbar.get_xlim()

        if self.bShowSeqPlot == False:
            axErrorbar.set_yticks(np.arange(len(features)))
            axErrorbar.set_yticklabels(features, size=8)
            axErrorbar.set_ylim([-1, len(features)])

            for label in axErrorbar.get_yticklabels():
                label.set_size(8)
                if label.get_text(
                ) in self.preferences['Selected statistical features']:
                    label.set_color('red')
        else:
            for label in axErrorbar.get_yticklabels():
                label.set_visible(False)

            for a in axErrorbar.yaxis.majorTicks:
                a.set_visible(False)

        for label in axErrorbar.get_xticklabels():
            label.set_size(8)

        for a in axErrorbar.xaxis.majorTicks:
            a.tick1On = True
            a.tick2On = False

        for a in axErrorbar.yaxis.majorTicks:
            a.tick1On = False
            a.tick2On = False

        for loc, spine in axErrorbar.spines.iteritems():
            if loc in ['left', 'right', 'top']:
                if loc != 'left' or (loc == 'left' and
                                     (self.bShowSeqPlot == True
                                      or bShowPowerPlot == True
                                      or self.bShowPValueLabels == False)):
                    spine.set_color('none')

        # *** Plot results of power test for each subsystem
        if bShowPowerPlot == True:
            lastAxes = axPower
            axPower.scatter(power,
                            np.arange(len(features)),
                            s=20,
                            facecolor=orangeColour,
                            edgecolor='none',
                            marker='^',
                            linewidth=1,
                            zorder=10)
            axPower.vlines(0.5,
                           -1,
                           len(features),
                           linestyle='dashed',
                           color=(0.25, 0.25, 0.25))
            for value in np.arange(-0.5, len(features) - 1, 2):
                axPower.axhspan(value,
                                value + 1,
                                facecolor=highlightColor,
                                edgecolor='none',
                                zorder=1)
            axPower.set_xlabel('Power', fontsize=8)
            axPower.set_xticks([0, 0.5, 1.0])
            axPower.set_xlim(-0.1, 1.1)
            axPower.set_ylim(-1, len(features))

            for label in axPower.get_xticklabels():
                label.set_size(8)

            for label in axPower.get_yticklabels():
                label.set_visible(False)

            for a in axPower.yaxis.majorTicks:
                a.set_visible(False)

            for a in axPower.xaxis.majorTicks:
                a.tick1On = True
                a.tick2On = False

            for loc, spine in axPower.spines.iteritems():
                if loc in ['left', 'right', 'top']:
                    spine.set_color('none')

        # *** Show p-values on right of last plot
        if self.bShowPValueLabels == True:
            axRight = lastAxes.twinx()
            axRight.set_yticks(np.arange(len(pValueLabels)))
            axRight.set_yticklabels(pValueLabels, size=8)
            axRight.set_ylim([-1, len(pValueLabels)])
            axRight.set_ylabel(pValueTitle, fontsize=8)
            if bShowPowerPlot == True:
                axRight.set_xticks([0, 0.5, 1.0])

            for a in axRight.yaxis.majorTicks:
                a.tick1On = False
                a.tick2On = False

            for label in axRight.get_yticklabels():
                label.set_size(8)

            for loc, spine in axRight.spines.iteritems():
                if loc in ['left', 'right', 'top']:
                    spine.set_color('none')

        self.updateGeometry()
        self.draw()
Exemple #23
0
def create_scatterhist(all_parameters,
                       parameter1,
                       parameter2,
                       measured,
                       modelled,
                       pars_names,
                       objective_function='SSE',
                       colormaps="red_yellow_green",
                       threshold=0.005,
                       *args,
                       **kwargs):
    '''
    Function to create the interactive scatterplot. Behavioural is always taken
    as lower as the given threshold.
    Parameters
    ----------
    all_parameters : Nxp np.array
        A number of parameter (p) value combinations used as model input. Length N
        corresponds to the number of simulations
        
    parameter1, parameter 2: {parametername : value}
        Parametername of the parameters that the user wants to use for 
        model evaluation
        
    modelled: Nxk np.array
        simulation outputs for all parameterscombinations (N). Length k is the length 
        of the timeserie
        
    measured: 1xk np.array
        observations. Length k is the length 
        of the timeserie
        
    parsnames: {parametername : value}
        dict with all parameters (p) used the model
        
    objective_function : Nx1 np.array
        The user is allowed to choose between different objective functions
        (SSE, RMSE, RRMSE)
        
                
    colormaps : 
        Colormap of the scatterplot 
        
     treshold : 
        Value between 0 and 1. Parametersets for which the scaled value of the
        objective function < threshold are retained (these parametersets are behavioral).
            
    *args,  **kwargs: args
        arguments given to the scatter plot
        example: s=15, marker='o', edgecolors= 'k', facecolor = 'white'
    ...
    '''

    # Extract values from pd dataframes
    all_parameters = all_parameters.values
    measured = measured.values
    modelled = modelled.values
    selected_of = _define_thresholdrange(measured, modelled,
                                         objective_function)

    #Translate color into a colormap
    colormaps = translate_cmap(colormaps)

    #Selected parameters & objective function
    parameters = np.vstack(
        (all_parameters[:, parameter1], all_parameters[:, parameter2])).T
    scaled_of = np.array((selected_of - selected_of.min()) /
                         (selected_of.max() - selected_of.min()))

    #calculation of the real threshold value from the relative one
    real_threshold = threshold * (selected_of.max() -
                                  selected_of.min()) + selected_of.min()
    print("Current threshold = " + str(real_threshold))

    #check if selected parameter are not the same
    if parameter1 == parameter2:
        raise Exception('Select two different parameters')

    #check if parameter and of are really arrays
    if not isinstance(parameters, np.ndarray):
        raise Exception('parameters need to be numpy ndarray')
    if not isinstance(scaled_of, np.ndarray):
        raise Exception('objective function need to be numpy ndarray')

    # check if objective function is of size 1xN
    scaled_of = np.atleast_2d(scaled_of).T
    if (len(scaled_of.shape) != 2):
        raise Exception(
            "Objective function need to be of size (1, N) got %s instead" %
            (scaled_of.shape))

    # check that SSE row length is equal to parameters
    if not parameters.shape[0] == scaled_of.shape[0]:
        raise Exception("None corresponding size of parameters and OF!")

    # Check if threshold is in range of SSE values
    if threshold < 0 or threshold > 1:
        raise Exception("Threshold outside objective function ranges")

    # Select behavioural parameter sets with of lower as threshold
    search = np.where(scaled_of < threshold)
    behav_par = parameters[search[0]]
    behav_obj = selected_of[search[0]].T
    print("Number of behavioural parametersets = " + str(behav_obj.shape[0]) +
          " out of " + str(parameters.shape[0]))

    if not behav_par.size > 0:
        raise Exception('Threshold to severe, no behavioural sets.')

    fig, ax_scatter = plt.subplots(figsize=(8, 6))
    divider = make_axes_locatable(ax_scatter)
    ax_scatter.set_autoscale_on(True)

    # create a new axes with  above the axScatter
    ax_histx = divider.new_vertical(1.5, pad=0.0001, sharex=ax_scatter)

    # create a new axes on the right side of the axScatter
    ax_histy = divider.new_horizontal(1.5, pad=0.0001, sharey=ax_scatter)

    fig.add_axes(ax_histx)
    fig.add_axes(ax_histy)

    # now determine nice limits by hand:
    xmin = np.min(all_parameters[:, parameter1])
    xmax = np.max(all_parameters[:, parameter1])
    ymin = np.min(all_parameters[:, parameter2])
    ymax = np.max(all_parameters[:, parameter2])

    ax_histx.set_xlim((xmin, xmax))
    ax_histy.set_ylim((ymin, ymax))

    #determine binwidth (pylab examples:scatter_hist.py )
    binwidth = 0.05
    xymax = np.max([np.max(behav_par[:, 0]), np.max(behav_par[:, 1])])
    lim = (int(xymax / binwidth) + 1) * binwidth

    bins = np.arange(-lim, lim + binwidth, binwidth)

    # create scatter & histogram
    sc1 = ax_scatter.scatter(behav_par[:, 0],
                             behav_par[:, 1],
                             c=behav_obj,
                             edgecolors='none',
                             cmap=colormaps,
                             *args,
                             **kwargs)
    ax_histx.hist(behav_par[:, 0], color='0.6', edgecolor='None', bins=bins)
    ax_histy.hist(behav_par[:, 1],
                  orientation='horizontal',
                  edgecolor='None',
                  color='0.6',
                  bins=bins)

    #determine number of bins scatter
    majloc1 = MaxNLocator(nbins=5, prune='lower')
    ax_scatter.yaxis.set_major_locator(majloc1)
    majloc2 = MaxNLocator(nbins=5)
    ax_scatter.xaxis.set_major_locator(majloc2)

    ax_scatter.grid(linestyle='dashed', color='0.75', linewidth=1.)
    ax_scatter.set_axisbelow(True)

    #ax_histx.set_axisbelow(True)

    plt.setp(ax_histx.get_xticklabels() + ax_histy.get_yticklabels(),
             visible=False)
    plt.setp(ax_histx.get_yticklabels() + ax_histy.get_xticklabels(),
             visible=False)
    ax_histy.set_xticks([])
    ax_histx.set_yticks([])
    ax_histx.xaxis.set_ticks_position('bottom')
    ax_histy.yaxis.set_ticks_position('left')

    ax_histy.spines['right'].set_color('none')
    ax_histy.spines['top'].set_color('none')
    ax_histy.spines['bottom'].set_color('none')
    ax_histy.spines['left'].set_color('none')

    ax_histx.spines['top'].set_color('none')
    ax_histx.spines['right'].set_color('none')
    ax_histx.spines['left'].set_color('none')
    ax_histx.spines['bottom'].set_color('none')
    ax_scatter.spines['top'].set_color('none')
    ax_scatter.spines['right'].set_color('none')

    # x and y label of parameter names
    ax_scatter.set_xlabel(pars_names[parameter1],
                          horizontalalignment='center',
                          verticalalignment='center')
    ax_scatter.set_ylabel(pars_names[parameter2],
                          horizontalalignment='center',
                          verticalalignment='center')

    # Colorbar
    cbar = fig.colorbar(sc1,
                        ax=ax_scatter,
                        cmap=colormaps,
                        orientation='vertical')
    cbar.ax.set_ylabel('Value objective function')

    behav_outputs = modelled[search[0]]

    return fig, ax_scatter, ax_histx, ax_histy, sc1, cbar, behav_outputs
Exemple #24
0
    def plot(self, profile, statsResults):
        # *** Check if there is sufficient data to generate the plot
        if len(statsResults.activeData) <= 0:
            self.emptyAxis()
            return

        features = statsResults.getColumn('Features')
        if len(features) > 200:
            QtGui.QApplication.instance().setOverrideCursor(
                QtGui.QCursor(QtCore.Qt.ArrowCursor))
            reply = QtGui.QMessageBox.question(
                self, 'Continue?',
                'Profile contains ' + str(len(features)) + ' features. ' +
                'It may take several seconds to generate this plot. We recommend filtering your profile first. '
                + 'Do you wish to continue?', QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No)
            QtGui.QApplication.instance().restoreOverrideCursor()
            if reply == QtGui.QMessageBox.No:
                self.emptyAxis()
                return

        # *** Colour of plot elements
        axesColour = str(self.preferences['Axes colour'].name())
        group1Colour = str(
            self.preferences['Group colours'][profile.groupName1].name())
        group2Colour = str(
            self.preferences['Group colours'][profile.groupName2].name())

        # *** Colour of plot elements
        highlightColor = (0.9, 0.9, 0.9)

        # *** Sort data
        if self.sortingField == 'p-values':
            statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\
                                     [statsResults.dataHeadings['pValues']], False)
        elif self.sortingField == 'Effect sizes':
            statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\
                                     [statsResults.dataHeadings['EffectSize']],
                                     True, True, False)

        elif self.sortingField == 'Feature labels':
            statsResults.activeData = TableHelper.SortTableStrCol(statsResults.activeData,\
                                     statsResults.dataHeadings['Features'], False)

        features = statsResults.getColumn(
            'Features')  # get sorted feature labels

        # *** Create lists for each quantity of interest
        if statsResults.multCompCorrection.method == 'False discovery rate':
            pValueTitle = 'q-value'
        else:
            pValueTitle = 'p-value'

        if self.bShowCorrectedPvalues:
            pValueLabels = statsResults.getColumnAsStr('pValuesCorrected')
            pValueTitle += ' (corrected)'
        else:
            pValueLabels = statsResults.getColumnAsStr('pValues')

        effectSizes = statsResults.getColumn('EffectSize')

        lowerCIs = statsResults.getColumn('LowerCI')
        upperCIs = statsResults.getColumn('UpperCI')
        ciTitle = (
            '%.3g' %
            (statsResults.oneMinusAlpha() * 100)) + '% confidence intervals'

        # *** Truncate feature labels
        highlightedFeatures = list(
            self.preferences['Highlighted group features'])
        if self.preferences['Truncate feature names']:
            length = self.preferences['Length of truncated feature names']

            for i in xrange(0, len(features)):
                if len(features[i]) > length + 3:
                    features[i] = features[i][0:length] + '...'

            for i in xrange(0, len(highlightedFeatures)):
                if len(highlightedFeatures[i]) > length + 3:
                    highlightedFeatures[
                        i] = highlightedFeatures[i][0:length] + '...'

        # *** Check that there is at least one significant feature
        if len(features) <= 0:
            self.emptyAxis('No significant features')
            return

        # *** Adjust effect size for axis scale
        dominateInSample2 = []
        percentage1 = []
        percentage2 = []
        for i in xrange(0, len(effectSizes)):
            if statsResults.bConfIntervRatio:
                if effectSizes[i] < 1:
                    # mirror CI across y-axis
                    effectSizes[i] = 1.0 / effectSizes[i]
                    lowerCI = effectSizes[i] - (1.0 / upperCIs[i])
                    upperCI = (1.0 / lowerCIs[i]) - effectSizes[i]

                    lowerCIs[i] = lowerCI
                    upperCIs[i] = upperCI

                    dominateInSample2.append(i)
                else:
                    lowerCIs[i] = effectSizes[i] - lowerCIs[i]
                    upperCIs[i] = upperCIs[i] - effectSizes[i]
            else:
                lowerCIs[i] = effectSizes[i] - lowerCIs[i]
                upperCIs[i] = upperCIs[i] - effectSizes[i]
                if effectSizes[i] < 0.0:
                    dominateInSample2.append(i)

        # *** Set figure size
        if self.legendPos == 3 or self.legendPos == 4 or self.legendPos == 8:  # bottom legend
            heightBottomLabels = 0.56  # inches
        else:
            heightBottomLabels = 0.4  # inches

        heightTopLabels = 0.25
        plotHeight = self.figHeightPerRow * len(features)
        self.imageWidth = self.figWidth
        self.imageHeight = plotHeight + heightBottomLabels + heightTopLabels
        if self.imageWidth > 256 or self.imageHeight > 256:
            QtGui.QApplication.instance().setOverrideCursor(
                QtGui.QCursor(QtCore.Qt.ArrowCursor))
            self.emptyAxis()
            reply = QtGui.QMessageBox.question(
                self, 'Excessively large plot',
                'The resulting plot is too large to display.')
            QtGui.QApplication.instance().restoreOverrideCursor()
            return

        self.fig.set_size_inches(self.imageWidth, self.imageHeight)

        # *** Determine width of y-axis labels
        yLabelBounds = self.yLabelExtents(features, 8)

        # *** Size plots which comprise the extended errorbar plot
        self.fig.clear()

        spacingBetweenPlots = 0.25  # inches
        widthNumSeqPlot = 1.25  # inches
        if self.bShowBarPlot == False:
            widthNumSeqPlot = 0.0
            spacingBetweenPlots = 0.0

        widthPvalueLabels = 0.75  # inches
        if self.bShowPValueLabels == False:
            widthPvalueLabels = 0.1

        yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight
        heightPlotFigSpace = plotHeight / self.imageHeight

        xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth
        pValueLabelWidthFigSpace = widthPvalueLabels / self.imageWidth
        widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace

        widthErrorBarPlot = widthPlotFigSpace * self.imageWidth - widthNumSeqPlot - spacingBetweenPlots

        axInitAxis = self.fig.add_axes([
            xPlotOffsetFigSpace, yPlotOffsetFigSpace, widthPlotFigSpace,
            heightPlotFigSpace
        ])
        divider = make_axes_locatable(axInitAxis)
        divider.get_vertical()[0] = Size.Fixed(
            len(features) * self.figHeightPerRow)

        if self.bShowBarPlot == True:
            divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot)
            axErrorbar = divider.new_horizontal(widthErrorBarPlot,
                                                pad=spacingBetweenPlots,
                                                sharey=axInitAxis)
            self.fig.add_axes(axErrorbar)
        else:
            divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot)
            axErrorbar = axInitAxis

        # *** Plot of sequences for each subsystem
        if self.bShowBarPlot == True:
            axNumSeq = axInitAxis

            meanRelFreqSeqs1 = statsResults.getColumn('MeanRelFreq1')
            meanRelFreqSeqs2 = statsResults.getColumn('MeanRelFreq2')

            if self.bShowStdDev:
                stdDev1 = statsResults.getColumn('StdDevRelFreq1')
                stdDev2 = statsResults.getColumn('StdDevRelFreq2')
                endCapSize = self.endCapSize
            else:
                stdDev1 = [0] * len(meanRelFreqSeqs1)
                stdDev2 = [0] * len(meanRelFreqSeqs2)
                endCapSize = 0

            axNumSeq.barh(np.arange(len(features)) + 0.0,
                          meanRelFreqSeqs1,
                          height=0.3,
                          xerr=stdDev1,
                          color=group1Colour,
                          ecolor='black',
                          capsize=endCapSize)
            axNumSeq.barh(np.arange(len(features)) - 0.3,
                          meanRelFreqSeqs2,
                          height=0.3,
                          xerr=stdDev2,
                          color=group2Colour,
                          ecolor='black',
                          capsize=endCapSize)
            for value in np.arange(-0.5, len(features) - 1, 2):
                axNumSeq.axhspan(value,
                                 value + 1,
                                 facecolor=highlightColor,
                                 edgecolor='none',
                                 zorder=-1)

            axNumSeq.set_xlabel('Mean proportion (%)')
            maxPercentage = max(max(meanRelFreqSeqs1), max(meanRelFreqSeqs2))
            axNumSeq.set_xticks([0, maxPercentage])
            axNumSeq.set_xlim([0, maxPercentage * 1.05])
            maxPercentageStr = '%.1f' % maxPercentage
            axNumSeq.set_xticklabels(['0.0', maxPercentageStr])

            axNumSeq.set_yticks(np.arange(len(features)))
            axNumSeq.set_yticklabels(features)
            axNumSeq.set_ylim([-1, len(features)])

            for label in axNumSeq.get_yticklabels():
                if label.get_text() in highlightedFeatures:
                    label.set_color('red')

            for a in axNumSeq.yaxis.majorTicks:
                a.tick1On = False
                a.tick2On = False

            for a in axNumSeq.xaxis.majorTicks:
                a.tick1On = True
                a.tick2On = False

            for line in axNumSeq.yaxis.get_ticklines():
                line.set_color(axesColour)

            for line in axNumSeq.xaxis.get_ticklines():
                line.set_color(axesColour)

            for loc, spine in axNumSeq.spines.iteritems():
                if loc in ['left', 'right', 'top']:
                    spine.set_color('none')
                else:
                    spine.set_color(axesColour)

        # *** Plot confidence intervals for each subsystem
        lastAxes = axErrorbar
        markerSize = math.sqrt(float(self.markerSize))
        axErrorbar.errorbar(effectSizes,
                            np.arange(len(features)),
                            xerr=[lowerCIs, upperCIs],
                            fmt='o',
                            ms=markerSize,
                            mfc=group1Colour,
                            mec='black',
                            ecolor='black',
                            zorder=10)
        effectSizesSample2 = [
            effectSizes[value] for value in dominateInSample2
        ]
        axErrorbar.plot(effectSizesSample2,
                        dominateInSample2,
                        ls='',
                        marker='o',
                        ms=markerSize,
                        mfc=group2Colour,
                        mec='black',
                        zorder=100)

        if statsResults.bConfIntervRatio:
            axErrorbar.vlines(1,
                              -1,
                              len(features),
                              linestyle='dashed',
                              color=axesColour)
        else:
            axErrorbar.vlines(0,
                              -1,
                              len(features),
                              linestyle='dashed',
                              color=axesColour)

        for value in np.arange(-0.5, len(features) - 1, 2):
            axErrorbar.axhspan(value,
                               value + 1,
                               facecolor=highlightColor,
                               edgecolor='none',
                               zorder=1)

        axErrorbar.set_title(ciTitle)
        axErrorbar.set_xlabel('Difference in mean proportions (%)')

        if self.bCustomLimits:
            axErrorbar.set_xlim([self.minX, self.maxX])
        else:
            self.minX, self.maxX = axErrorbar.get_xlim()

        if self.bShowBarPlot == False:
            axErrorbar.set_yticks(np.arange(len(features)))
            axErrorbar.set_yticklabels(features)
            axErrorbar.set_ylim([-1, len(features)])

            for label in axErrorbar.get_yticklabels():
                if label.get_text(
                ) in self.preferences['Highlighted group features']:
                    label.set_color('red')
        else:
            for label in axErrorbar.get_yticklabels():
                label.set_visible(False)

            for a in axErrorbar.yaxis.majorTicks:
                a.set_visible(False)

        for a in axErrorbar.xaxis.majorTicks:
            a.tick1On = True
            a.tick2On = False

        for a in axErrorbar.yaxis.majorTicks:
            a.tick1On = False
            a.tick2On = False

        for line in axErrorbar.yaxis.get_ticklines():
            line.set_visible(False)

        for line in axErrorbar.xaxis.get_ticklines():
            line.set_color(axesColour)

        for loc, spine in axErrorbar.spines.iteritems():
            if loc in ['left', 'right', 'top']:
                spine.set_color('none')
            else:
                spine.set_color(axesColour)

        # *** Show p-values on right of last plot
        if self.bShowPValueLabels == True:
            axRight = lastAxes.twinx()
            axRight.set_yticks(np.arange(len(pValueLabels)))
            axRight.set_yticklabels(pValueLabels)
            axRight.set_ylim([-1, len(pValueLabels)])
            axRight.set_ylabel(pValueTitle)

            for a in axRight.yaxis.majorTicks:
                a.tick1On = False
                a.tick2On = False

        # *** Legend
        if self.legendPos != -1:
            legend1 = Rectangle((0, 0), 1, 1, fc=group1Colour)
            legend2 = Rectangle((0, 0), 1, 1, fc=group2Colour)
            legend = self.fig.legend([legend1, legend2],
                                     (profile.groupName1, profile.groupName2),
                                     loc=self.legendPos,
                                     ncol=2)
            legend.get_frame().set_linewidth(0)

        self.updateGeometry()
        self.draw()
Exemple #25
0
from mpl_toolkits.axes_grid import make_axes_locatable
import  matplotlib.axes as maxes
from matplotlib import cm

if __name__ == '__main__':

    fig = P.figure(figsize=(10,10))
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(224)

    s1 = ax1.scatter(numpy.random.rand(10),
                     numpy.random.rand(10),
                     c=numpy.random.rand(10))
    divider = make_axes_locatable(ax1)
    cax1 = divider.new_horizontal('5%', pad=0.0, axes_class=maxes.Axes)
    fig.add_axes(cax1)
    c1 = fig.colorbar(s1, cax = cax1,orientation = 'horizontal')

    s2 = ax2.scatter(numpy.random.rand(10),
                     numpy.random.rand(10),
                     c=numpy.random.rand(10),
                     cmap = cm.get_cmap('jet'))
    divider = make_axes_locatable(ax2)
    cax2 = divider.append_axes('right', 0.1, pad=0.1)
    c2 = fig.colorbar(s2, cax = cax2)
    #p =  matplotlib.patches.Patch(color=cm.get_cmap('jet'))
    #ax2.legend([p],['Test'])

    s3 = ax3.scatter(numpy.random.rand(10),
def histogram(values, label_x=None, label_y=None, color="#00ff00", size=(650,650)):
    """
    Values will come as a list of tuples representing (x,y) values.
    
    values  = [(0,100),(15,2500),(20,3000),(25,2700),(30,2800),(35,3600),(40,4200),(45,3500),(50,2100)]
    label_x = "Age"
    label_y = "Population"
    """
   
    # unpack the tuple value list into x and y lists
    x_vals = []; y_vals = []
    for tuple in values:
        first, second = tuple;
        x_vals.append(first)
        y_vals.append(second)

    tick_val = max(min(x_vals, y_vals))

    # convert the data to a numpy list
    x = np.array(x_vals)
    y = np.array(y_vals)

    # the width and height of the figure
    fig_w = int(size[0])/100
    fig_h = int(size[1])/100

    # set up the graph descriptor object and prefrences for it
    fig = Figure(figsize=(fig_w,fig_h), dpi=100, facecolor='#ffffff', frameon=False)

    axScatter = fig.add_subplot(111)

    axScatter.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)
    axScatter.xaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)

    divider = make_axes_locatable(axScatter)

    # create a new axes with a height of 1.2 inch above the axScatter
    axHistx = divider.new_vertical(1.2, pad=0.1, sharex=axScatter)
    axHistx.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)
    axHistx.xaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)
    
    # create a new axes with a width of 1.2 inch on the right side of the axScatter
    axHisty = divider.new_horizontal(1.2, pad=0.1, sharey=axScatter)
    axHisty.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)
    axHisty.xaxis.grid(True, linestyle='-', which='major', color='lightgrey',alpha=0.5)    

    fig.add_axes(axHistx)
    fig.add_axes(axHisty)

    # plot the scatterplot and set aspect ratio, grid lines
    axScatter.scatter(x, y, facecolors=color)
    axScatter.set_aspect("auto")
    axScatter.grid(True)

    # now determine limits manually and set the bin number
    binwidth = 0.25
    #xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
    #lim = ( int(xymax/binwidth) + 1) * binwidth
    #bins = np.arange(-lim, lim + binwidth, binwidth)

    # plot the histograms for x and y
    axHistx.hist(x, bins=9, facecolor=color, alpha=0.75)
    axHisty.hist(y, bins=9, orientation='horizontal', facecolor=color, alpha=0.75)

    # the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
    # thus there is no need to manually adjust the xlim and ylim of these
    # axis.

    # axHistx.axis["bottom"].major_ticklabels.set_visible(False)
    for tl in axHistx.get_xticklabels():
        tl.set_visible(False)
    axHistx.set_yticks([0, int(tick_val/8), int(tick_val/4)])
    axHistx.set_title(label_x)
    # axHisty.axis["left"].major_ticklabels.set_visible(False)
    for tl in axHisty.get_yticklabels():
        tl.set_visible(False)
    axHisty.set_xticks([0, int(tick_val/8), int(tick_val/4)])
    axHisty.set_title(label_y)

    return fig
def create_scatterhist(all_parameters, parameter1, parameter2, objective,
                        pars_names, xbinwidth = 0.05, ybinwidth = 0.05,
                        objective_function='SSE', 
                        colormaps = "red_yellow_green",
                        threshold=0.02,
                        season = 'Winter', 
                        *args,  **kwargs):
                            
    '''
    Function to create the interactive scatterplot. Behavioural is always taken
    as lower as the given threshold.

    Parameters
    ----------
    all_parameters : Nxp np.array
        A number of parameter (p) value combinations used as model input. Length N
        corresponds to the number of simulations
        
    parameter1, parameter 2: {parametername : value}
        Parametername of the parameters that the user wants to use for 
        model evaluation
        
    objective: nxk pd.Dataframe
        Values of objective function for all simulations (n) and for all possible combination (k)
        of seasons and criteria (SSE, RMSE, RRMSE). Each column contains the
        the objective function values for all simulations calculated
        for a selected criteria (SSE, RMSE, RRMSE) based on the whole dateset 
        or on a subdataset (specific season).
        
    parsnames: {parametername : value}
        dict with all parameters (p) used the model
    
    xbinwidth: float
        defines the width of the xbin to the data used
        
    ybinwidth: float
        defines the width of the ybin to the data used
        
    objective_function : Nx1 np.array
        The user is allowed to choose between different objective functions
        (SSE, RMSE, RRMSE)
                        
    colormaps : 
        Colormap of the scatterplot 
        
     treshold : 
        Value between 0 and 1. Parametersets for which the scaled value of the
        objective function < threshold are retained (these parametersets are behavioral).
            
    *args,  **kwargs: args
        arguments given to the scatter plot
        example: s=15, marker='o', edgecolors= 'k', facecolor = 'white'
        
    Returns
    ---------
    fig: matplotlib.figure.Figure object
        the resulting figure
    axScatter: matplotlib.axes.AxesSubplot object
        the scatter plot with the datapoints, can be used to add labels or
        change the current ticks settings
    axHistx: matplotlib.axes.AxesSubplot object
        the x-axis histogram
    axHisty: matplotlib.axes.AxesSubplot object
        the y-axis histogram
    ...
    '''
        
    # Selected season & objective_function
    all_parameters=all_parameters.values
    selected_of= _select_season_OF(objective,season,objective_function)
    
    #Translate color into a colormap
    colormaps = translate_cmap(colormaps)
    
    #Selected parameters & objective function 
    parameters = np.vstack((all_parameters[:,parameter1], all_parameters[:,parameter2])).T
    scaled_of = np.array((selected_of-selected_of.min())/(selected_of.max()-selected_of.min()))
    
    #calculation of the real threshold value from the relative one
    real_threshold = threshold*(selected_of.max() - selected_of.min())+selected_of.min()
    print("Current threshold = " + str(real_threshold))
    
       
    #check if selected parameter are not the same
    if parameter1 == parameter2:
        raise Exception('Select two different parameters')
          
    #check if parameter and of are really arrays
    if not isinstance(parameters, np.ndarray):
        raise Exception('parameters need to be numpy ndarray')
    if not isinstance(scaled_of, np.ndarray):
        raise Exception('objective function need to be numpy ndarray')

    # check if objective function is of size 1xN     
    scaled_of = np.atleast_2d(scaled_of).T
    if (len(scaled_of.shape) != 2 ):
       raise Exception("Objective function need to be of size (1, N) got %s instead" %(scaled_of.shape))
   
    # check that SSE row length is equal to parameters
    if not parameters.shape[0] == scaled_of.shape[0]:
        raise Exception("None corresponding size of parameters and OF!")

    # Check if threshold is in range of SSE values
    if threshold < 0 or threshold > 1:
        raise Exception("Threshold outside objective function ranges")

    # Select behavioural parameter sets with of lower as threshold
    search=np.where(scaled_of < threshold)
    behav_par = parameters[search[0]]
    behav_obj = selected_of[search[0]].T 
    print("Number of behavioural parametersets = " + str(behav_obj.shape[0]) + " out of " + str(parameters.shape[0]))
    
    
    if not behav_par.size > 0:
        raise Exception('Threshold to severe, no behavioural sets.')

        
    fig, ax_scatter = plt.subplots(figsize=(8,6))
    divider = make_axes_locatable(ax_scatter)
    ax_scatter.set_autoscale_on(True)
      
        
    # create a new axes with  above the axScatter
    ax_histx = divider.new_vertical(1.5, pad=0.0001, sharex=ax_scatter)

    # create a new axes on the right side of the axScatter
    ax_histy = divider.new_horizontal(1.5, pad=0.0001, sharey=ax_scatter)

    fig.add_axes(ax_histx)
    fig.add_axes(ax_histy)
    

    # now determine nice limits by hand:
    xmin = np.min(all_parameters[:,parameter1])
    xmax = np.max(all_parameters[:,parameter1])
    ymin = np.min(all_parameters[:,parameter2])
    ymax = np.max(all_parameters[:,parameter2])
    
    ax_histx.set_xlim( (xmin, xmax) )
    ax_histy.set_ylim( (ymin, ymax) )

    #determine binwidth (pylab examples:scatter_hist.py )
    
    xbinwidth = (xmax-xmin)*xbinwidth
    binsx = np.arange(xmin,xmax+xbinwidth,xbinwidth)
    
    ybinwidth = (ymax-ymin)*ybinwidth
    binsy = np.arange(ymin,ymax+ybinwidth,ybinwidth)

        
    # create scatter & histogram
    sc1 = ax_scatter.scatter(behav_par[:,0], behav_par[:,1], c=behav_obj,
                             edgecolors= 'none', cmap=colormaps, *args,  **kwargs)
    ax_histx.hist(behav_par[:,0], color='0.6', edgecolor='None',  bins = binsx)
    ax_histy.hist(behav_par[:,1], orientation='horizontal',  edgecolor='None',
                  color='0.6', bins=binsy)
                  
    #determine number of bins scatter              
    majloc1 = MaxNLocator(nbins=5, prune='lower')
    ax_scatter.yaxis.set_major_locator(majloc1)
    majloc2 = MaxNLocator(nbins=5)
    ax_scatter.xaxis.set_major_locator(majloc2)

    ax_scatter.grid(linestyle = 'dashed', color = '0.75',linewidth = 1.)
    ax_scatter.set_axisbelow(True)
    
    
    #ax_histx.set_axisbelow(True)


    plt.setp(ax_histx.get_xticklabels() + ax_histy.get_yticklabels(),
            visible=False)
    plt.setp(ax_histx.get_yticklabels() + ax_histy.get_xticklabels(),
            visible=False)
    ax_histy.set_xticks([])
    ax_histx.set_yticks([])
    ax_histx.xaxis.set_ticks_position('bottom')
    ax_histy.yaxis.set_ticks_position('left')

    ax_histy.spines['right'].set_color('none')
    ax_histy.spines['top'].set_color('none')
    ax_histy.spines['bottom'].set_color('none')
    ax_histy.spines['left'].set_color('none')

    ax_histx.spines['top'].set_color('none')
    ax_histx.spines['right'].set_color('none')
    ax_histx.spines['left'].set_color('none')
    ax_histx.spines['bottom'].set_color('none')
    ax_scatter.spines['top'].set_color('none')
    ax_scatter.spines['right'].set_color('none')


   # x and y label of parameter names
    ax_scatter.set_xlabel(pars_names[parameter1], horizontalalignment ='center', verticalalignment ='center')    
    ax_scatter.set_ylabel(pars_names[parameter2], horizontalalignment ='center', verticalalignment ='center')    
  
    # Colorbar
    cbar = fig.colorbar(sc1, ax=ax_scatter, cmap=colormaps,
                        orientation='vertical')
    cbar.ax.set_ylabel('Value objective function')
    
       
    return fig, ax_scatter, ax_histx, ax_histy, sc1, cbar
Exemple #28
0
def plot(axes, net):

    classname = net.__class__.__name__

    axes.set_xticks([])
    axes.set_yticks([])
    divider = make_axes_locatable(axes)
    subaxes = divider.new_vertical(1.0, pad=0.4, sharex=axes)
    fig.add_axes(subaxes)
    subaxes.set_xticks([])
    subaxes.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
    subaxes.yaxis.set_ticks_position('right')
    subaxes.set_ylabel('Distortion')
    subaxes.set_xlabel('Time')

    Y = net.distortion[::1]
    X = np.arange(len(Y)) / float(len(Y) - 1)
    subaxes.plot(X, Y)

    if classname == 'NG':
        plt.title('Neural Gas', fontsize=20)
    elif classname == 'SOM':
        plt.title('Self-Organizing Map', fontsize=20)
    elif classname == 'DSOM':
        plt.title('Dynamic Self-Organizing Map', fontsize=20)

    axes.axis([0, 1, 0, 1])
    axes.set_aspect(1)

    codebook = net.codebook
    axes.imshow(codebook, interpolation='nearest')
    #interpolation='bicubic')

    if classname == 'NG':
        axes.text(
            0.5,
            -0.01,
            r'$\lambda_i = %.3f,\lambda_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$'
            % (net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
            fontsize=16,
            horizontalalignment='center',
            verticalalignment='top',
            transform=axes.transAxes)
    if classname == 'SOM':
        axes.text(
            0.5,
            -0.01,
            r'$\sigma_i = %.3f,\sigma_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$'
            % (net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
            fontsize=16,
            horizontalalignment='center',
            verticalalignment='top',
            transform=axes.transAxes)
    elif classname == 'DSOM':
        axes.text(0.5,
                  -0.01,
                  r'$elasticity = %.2f$' % (net.elasticity),
                  fontsize=16,
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform=axes.transAxes)
Exemple #29
0
	def plot(self, profile, statsResults):
		# *** Check if there is sufficient data to generate the plot
		if len(statsResults.activeData) <= 0:
			self.emptyAxis()
			return
		
		features = statsResults.getColumn('Features')
		if len(features) > 200:
			QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
			reply = QtGui.QMessageBox.question(self, 'Continue?', 'Profile contains ' + str(len(features)) + ' features. ' +
																		'It may take several seconds to generate this plot. We recommend filtering your profile first. ' + 
																		'Do you wish to continue?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			QtGui.QApplication.instance().restoreOverrideCursor()
			if reply == QtGui.QMessageBox.No:
				self.emptyAxis()	
				return

		
		# *** Colour of plot elements
		axesColour = str(self.preferences['Axes colour'].name())
		profile1Colour = str(self.preferences['Sample 1 colour'].name())
		profile2Colour = str(self.preferences['Sample 2 colour'].name())
						
		# *** Colour of plot elements
		highlightColor = (0.9, 0.9, 0.9)
		
		# *** Sort data
		if self.sortingField == 'p-values':
			statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\
																												[statsResults.dataHeadings['pValues']], False)
		elif self.sortingField == 'Effect sizes':
			statsResults.activeData = TableHelper.SortTable(statsResults.activeData,\
																												[statsResults.dataHeadings['EffectSize']], 
																												True, True, statsResults.confIntervMethod.bRatio)
			
		elif self.sortingField == 'Feature labels':
			statsResults.activeData = TableHelper.SortTableStrCol(statsResults.activeData,\
																												statsResults.dataHeadings['Features'], False)

		features = statsResults.getColumn('Features')	# get sorted feature labels
					
		# *** Create lists for each quantity of interest
		if statsResults.multCompCorrection.method == 'False discovery rate':
			pValueTitle = 'q-value'
		else:
			pValueTitle = 'p-value'

		if self.bShowCorrectedPvalues:
			pValueLabels = statsResults.getColumnAsStr('pValuesCorrected')
			if statsResults.multCompCorrection.method != 'No correction':
				pValueTitle += ' (corrected)'
		else:
			pValueLabels = statsResults.getColumnAsStr('pValues')
			
		effectSizes = statsResults.getColumn('EffectSize')
		
		lowerCIs = statsResults.getColumn('LowerCI')
		upperCIs = statsResults.getColumn('UpperCI')
		ciTitle = ('%.3g' % (statsResults.oneMinusAlpha()*100)) + '% confidence intervals'
			
		seqs1 = statsResults.getColumn('Seq1')
		seqs2 = statsResults.getColumn('Seq2')
		parentSeqs1 = statsResults.getColumn('ParentalSeq1')
		parentSeqs2 = statsResults.getColumn('ParentalSeq2')
		
		# *** Truncate feature labels
		highlightedFeatures = list(self.preferences['Highlighted sample features'])
		if self.preferences['Truncate feature names']:
			length = self.preferences['Length of truncated feature names']
			
			for i in xrange(0, len(features)):
				if len(features[i]) > length+3:
					features[i] = features[i][0:length] + '...'
								
			for i in xrange(0, len(highlightedFeatures)):
				if len(highlightedFeatures[i]) > length+3:
					highlightedFeatures[i] = highlightedFeatures[i][0:length] + '...'
				
		# *** Adjust effect size for axis scale
		dominateInSample2 = []
		percentage1 = []
		percentage2 = []
		for i in xrange(0, len(effectSizes)):
			percentage1.append(float(seqs1[i])*100 / parentSeqs1[i])
			percentage2.append(float(seqs2[i])*100 / parentSeqs2[i])
			
			if statsResults.confIntervMethod.bRatio:
				if effectSizes[i] < 1:
					# mirror CI across y-axis
					effectSizes[i] = 1.0 / effectSizes[i]
					lowerCI = effectSizes[i] - (1.0 / upperCIs[i])
					upperCI = (1.0 / lowerCIs[i]) - effectSizes[i]

					lowerCIs[i] = lowerCI
					upperCIs[i] = upperCI

					dominateInSample2.append(i)
				else:
					lowerCIs[i] = effectSizes[i] - lowerCIs[i]
					upperCIs[i] = upperCIs[i] - effectSizes[i] 
			else:
				lowerCIs[i] = effectSizes[i] - lowerCIs[i]
				upperCIs[i] = upperCIs[i] - effectSizes[i]
				if effectSizes[i] < 0.0:
					dominateInSample2.append(i)

		# *** Set figure size
		if self.legendPos == 3 or self.legendPos == 4 or self.legendPos == 8: # bottom legend
			heightBottomLabels = 0.56	# inches
		else:
			heightBottomLabels = 0.4	# inches
			
		heightTopLabels = 0.25
		plotHeight = self.figHeightPerRow*len(features) 
		self.imageWidth = self.figWidth
		self.imageHeight = plotHeight	+ heightBottomLabels + heightTopLabels
		if self.imageWidth > 256 or self.imageHeight > 256:
				QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
				self.emptyAxis()	
				reply = QtGui.QMessageBox.question(self, 'Excessively large plot', 'The resulting plot is too large to display.')
				QtGui.QApplication.instance().restoreOverrideCursor()
				return
		
		self.fig.set_size_inches(self.imageWidth, self.imageHeight)	
				
		# *** Determine width of y-axis labels
		yLabelBounds = self.yLabelExtents(features, 8)
		
		# *** Size plots which comprise the extended errorbar plot
		self.fig.clear()
		
		spacingBetweenPlots = 0.25	# inches
		widthNumSeqPlot = 1.25	# inches
		if self.bShowBarPlot == False:
			widthNumSeqPlot = 0.0
			spacingBetweenPlots = 0.0
		
		widthPvalueLabels = 0.75	# inches
		if self.bShowPValueLabels == False:
			widthPvalueLabels = 0.1
				 
		yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight 
		heightPlotFigSpace = plotHeight / self.imageHeight
			 
		xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth
		pValueLabelWidthFigSpace =	widthPvalueLabels / self.imageWidth
		widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace
		
		widthErrorBarPlot = widthPlotFigSpace*self.imageWidth - widthNumSeqPlot - spacingBetweenPlots
				
		axInitAxis = self.fig.add_axes([xPlotOffsetFigSpace,yPlotOffsetFigSpace,widthPlotFigSpace,heightPlotFigSpace])
		divider = make_axes_locatable(axInitAxis)
		divider.get_vertical()[0] = Size.Fixed(len(features)*self.figHeightPerRow)
	 
		if self.bShowBarPlot == True:	
			divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot)
			axErrorbar = divider.new_horizontal(widthErrorBarPlot, pad=spacingBetweenPlots, sharey=axInitAxis)
			self.fig.add_axes(axErrorbar)
		else:
			divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot)
			axErrorbar = axInitAxis
				
		# *** Plot of sequences for each subsystem
		if self.bShowBarPlot == True:
			axNumSeq = axInitAxis
			
			if self.percentageOrSeqCount == 'Proportion (%)':
				# plot percentage
				axNumSeq.barh(np.arange(len(features))+0.0, percentage1, height = 0.3, color=profile1Colour, zorder=10, ecolor='black')
				axNumSeq.barh(np.arange(len(features))-0.3, percentage2, height = 0.3, color=profile2Colour, zorder=10, ecolor='black')
				for value in np.arange(-0.5, len(features)-1, 2):
					axNumSeq.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1)
				
				axNumSeq.set_xlabel(self.percentageOrSeqCount)
				maxPercentage = max(max(percentage1), max(percentage2))
				axNumSeq.set_xticks([0, maxPercentage])
				axNumSeq.set_xlim([0, maxPercentage*1.05])
				maxPercentageStr = '%.1f' % maxPercentage
				axNumSeq.set_xticklabels(['0.0', maxPercentageStr])
			else:
				# plot sequence count
				axNumSeq.barh(np.arange(len(features))+0.0, seqs1, height = 0.3, color=profile1Colour, zorder=10, ecolor='black')
				axNumSeq.barh(np.arange(len(features))-0.3, seqs2, height = 0.3, color=profile2Colour, zorder=10, ecolor='black')
				for value in np.arange(-0.5, len(features)-1, 2):
					axNumSeq.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1)
				
				axNumSeq.set_xlabel(self.percentageOrSeqCount)
				maxSeqs = max(max(seqs1), max(seqs2))
				axNumSeq.set_xticks([0, maxSeqs])
				axNumSeq.set_xlim([0, maxSeqs*1.05])
				axNumSeq.set_xticklabels([0, str(maxSeqs)])
				
			axNumSeq.set_yticks(np.arange(len(features)))
			axNumSeq.set_yticklabels(features)
			axNumSeq.set_ylim([-1, len(features)])
			
			for label in axNumSeq.get_yticklabels():
				if label.get_text() in highlightedFeatures:
					label.set_color('red')
					
			for a in axNumSeq.yaxis.majorTicks:
				a.tick1On=False
				a.tick2On=False
					
			for a in axNumSeq.xaxis.majorTicks:
				a.tick1On=True
				a.tick2On=False
				
			for line in axNumSeq.yaxis.get_ticklines(): 
				line.set_color(axesColour)
				
			for line in axNumSeq.xaxis.get_ticklines(): 
				line.set_color(axesColour)
					
			for loc, spine in axNumSeq.spines.iteritems():
				if loc in ['left', 'right','top']:
					spine.set_color('none') 
				else:
					spine.set_color(axesColour)
						
		# *** Plot confidence intervals for each subsystem
		lastAxes = axErrorbar
		markerSize = math.sqrt(float(self.markerSize))
		axErrorbar.errorbar(effectSizes, np.arange(len(features)), xerr=[lowerCIs,upperCIs], fmt='o', ms=markerSize, mfc=profile1Colour, mec='black', ecolor='black', zorder=10)
		effectSizesSample2 = [effectSizes[value] for value in dominateInSample2]
		axErrorbar.plot(effectSizesSample2, dominateInSample2, ls='', marker='o', ms=markerSize, mfc=profile2Colour, mec='black', zorder=100)
		
		if statsResults.confIntervMethod.bRatio:
			axErrorbar.vlines(1, -1, len(features), linestyle='dashed', color=axesColour)
		else:
			axErrorbar.vlines(0, -1, len(features), linestyle='dashed', color=axesColour)
		
		for value in np.arange(-0.5, len(features)-1, 2):
			axErrorbar.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1)

		axErrorbar.set_title(ciTitle) 
		axErrorbar.set_xlabel(statsResults.confIntervMethod.plotLabel)
		
		if self.bCustomLimits:
			axErrorbar.set_xlim([self.minX, self.maxX])
		else:
			self.minX, self.maxX = axErrorbar.get_xlim()
 
		if self.bShowBarPlot == False:
			axErrorbar.set_yticks(np.arange(len(features)))
			axErrorbar.set_yticklabels(features)
			axErrorbar.set_ylim([-1, len(features)])
			
			for label in axErrorbar.get_yticklabels():
				if label.get_text() in highlightedFeatures:
					label.set_color('red')
		else:
			for label in axErrorbar.get_yticklabels():
				label.set_visible(False)
				
			for a in axErrorbar.yaxis.majorTicks:
				a.set_visible(False)
				
		for a in axErrorbar.xaxis.majorTicks:
			a.tick1On=True
			a.tick2On=False
				
		for a in axErrorbar.yaxis.majorTicks:
			a.tick1On=False
			a.tick2On=False
			
		for line in axErrorbar.yaxis.get_ticklines(): 
			line.set_visible(False)
				
		for line in axErrorbar.xaxis.get_ticklines(): 
			line.set_color(axesColour)

		for loc, spine in axErrorbar.spines.iteritems():
			if loc in ['left','right','top']:
				spine.set_color('none') 
			else:
				spine.set_color(axesColour)
						
		# *** Show p-values on right of last plot
		if self.bShowPValueLabels == True:
			axRight = lastAxes.twinx()
			axRight.set_yticks(np.arange(len(pValueLabels)))
			axRight.set_yticklabels(pValueLabels)
			axRight.set_ylim([-1, len(pValueLabels)])
			axRight.set_ylabel(pValueTitle)
			
			for a in axRight.yaxis.majorTicks:
				a.tick1On=False
				a.tick2On=False
				
			for loc, spine in axRight.spines.iteritems():
				spine.set_color('none') 
		
		# *** Legend
		# *** Legend
		if self.legendPos != -1:
			legend1 = Rectangle((0, 0), 1, 1, fc=profile1Colour)
			legend2 = Rectangle((0, 0), 1, 1, fc=profile2Colour)
			legend = self.fig.legend([legend1, legend2], (statsResults.profile.sampleNames[0], statsResults.profile.sampleNames[1]), loc=self.legendPos, ncol=2)
			legend.get_frame().set_linewidth(0)

		self.updateGeometry()
		self.draw()
Exemple #30
0
    def show(self,
             location='right',
             width=0.2,
             pad=0.05,
             ticks=None,
             labels=True,
             format=None,
             sig_digits=0,
             box=None,
             box_orientation='vertical',
             axis_label_text=None,
             axis_label_rotation=None,
             axis_label_pad=5):
        '''
        Show a colorbar on the side of the image.

        Parameters
        ----------

        location : str, optional
            Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

        width : float, optional
            The width of the colorbar relative to the canvas size.

        pad : float, optional
            The spacing between the colorbar and the image relative to the canvas size.

        ticks : list, optional
            The position of the ticks on the colorbar.

        labels : bool, optional
            Whether to show numerical labels.

        format : str, optional
            Format of the colorbar tick labels. Can be 'exp' (exponential 
            notation) or 'sci' (scientific notation). Default is None.

        sig_digits: int, optional
            Number of significant digits if format is set to 'sci'.

        box : list, optional
            A custom box within which to place the colorbar. This should
            be in the form [xmin, ymin, dx, dy] and be in relative figure
            units. This overrides the location argument.

        box_orientation str, optional
            The orientation of the colorbar within the box. Can be
            'horizontal' or 'vertical'

        axis_label_text str, optional
            Optional text label of the colorbar.
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['format'] = format
        self._base_settings['sig_digits'] = sig_digits
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self._base_settings['axis_label_text'] = axis_label_text
        self._base_settings['axis_label_rotation'] = axis_label_rotation
        self._base_settings['axis_label_pad'] = axis_label_pad

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent._ax1)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(
                        size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(
                        size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(
                        size=width,
                        pad=pad,
                        pack_start=True,
                        axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(
                        size=width,
                        pad=pad,
                        pack_start=True,
                        axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            if format == 'exp':
                format = LogFormatterMathtext()
            elif format == 'sci':
                format = '%.' + str(sig_digits) + 'e'
            else:
                format = None

            self._colorbar = self._parent._figure.colorbar(
                self._parent.image,
                cax=self._colorbar_axes,
                orientation=orientation,
                format=format,
                ticks=ticks)
            if axis_label_text:
                if axis_label_rotation:
                    self._colorbar.set_label(axis_label_text,
                                             rotation=axis_label_rotation)
                else:
                    self._colorbar.set_label(axis_label_text)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
                self._colorbar_axes.yaxis.set_label_position('right')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
                self._colorbar_axes.xaxis.set_label_position('top')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
                self._colorbar_axes.yaxis.set_label_position('left')
                self._colorbar_axes.yaxis.labelpad = axis_label_pad
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
                self._colorbar_axes.xaxis.set_label_position('bottom')
                self._colorbar_axes.xaxis.labelpad = axis_label_pad

        else:

            warnings.warn(
                "No image is shown, therefore, no colorbar will be plotted")
Exemple #31
0
    def show(self, location='right', width=0.2, pad=0.05, ticks=None, labels=True, box=None, box_orientation='vertical'):
        '''
        Show a colorbar on the side of the image.

        Optional Keyword Arguments:

            *location*: [ string ]
                Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

            *width*: [ float ]
                The width of the colorbar relative to the canvas size.

            *pad*: [ float ]
                The spacing between the colorbar and the image relative to the canvas size.

            *ticks*: [ None or list ]
                The position of the ticks on the colorbar.

            *labels*: [ True or False ]
                Whether to show numerical labels.

            *box*: [ list ]
                A custom box within which to place the colorbar. This should
                be in the form [xmin, ymin, dx, dy] and be in relative figure
                units. This overrides the location argument.

            *box_orientation* [ str ]
                The orientation of the colorbar within the box. Can be
                'horizontal' or 'vertical'
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent._ax1)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes, orientation=orientation, ticks=ticks)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False

        else:

            warnings.warn("No image is shown, therefore, no colorbar will be plotted")
Exemple #32
0
def save_pca(odir, filename, stk, anlz, png, pdf, svg):
    
    SaveFileName = os.path.join(odir,filename)
        
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    matplotlib.rcParams['pdf.fonttype'] = 42
    
    #Save evals
    evalmax = np.min([stk.n_ev, 40])
    pcaevals = anlz.eigenvals[0:evalmax]
    fig = matplotlib.figure.Figure(figsize =(PlotW, PlotH))
    canvas = FigureCanvas(fig)

    fig.clf()
    fig.add_axes((0.15,0.15,0.75,0.75))
    axes = fig.gca()
    
    evalsplot = axes.semilogy(np.arange(1,evalmax+1), pcaevals,'b.')    
    
    axes.set_xlabel('Principal Component')
    axes.set_ylabel('Log(Eigenvalue)')
     
     
    if png == 1:
        ext = 'png'
        fileName_evals = SaveFileName+"_PCAevals."+ext
        fig.savefig(fileName_evals, bbox_inches='tight', pad_inches = 0.0)
    if pdf == 1:
        ext = 'pdf'
        fileName_evals = SaveFileName+"_PCAevals."+ext
        fig.savefig(fileName_evals, bbox_inches='tight', pad_inches = 0.0)
    if svg == 1:
        ext = 'svg'
        fileName_evals = SaveFileName+"_PCAevals."+ext
        fig.savefig(fileName_evals, bbox_inches='tight', pad_inches = 0.0)
        
             
    for i in range(10):
    
        pcaimage = anlz.pcaimages[:,:,i]
    
        fig = matplotlib.figure.Figure(figsize =(PlotH*1.15, PlotH))
        canvas = FigureCanvas(fig)
        axes = fig.gca()
        divider = make_axes_locatable(axes)
        ax_cb = divider.new_horizontal(size="3%", pad=0.03)  
        fig.add_axes(ax_cb)
        axes.set_position([0.03,0.03,0.8,0.94])
        bound = anlz.pcaimagebounds[i]       
    
        im = axes.imshow(pcaimage, cmap=matplotlib.cm.get_cmap("seismic_r"), vmin = -bound, vmax = bound)
        cbar = axes.figure.colorbar(im, orientation='vertical',cax=ax_cb)  
        axes.axis("off") 

        if png == 1:
            ext = 'png'                     
            fileName_img = SaveFileName+"_PCA_" +str(i+1)+"."+ext
            fig.savefig(fileName_img, bbox_inches='tight', pad_inches = 0.0)
        if pdf == 1:
            ext = 'pdf'                     
            fileName_img = SaveFileName+"_PCA_" +str(i+1)+"."+ext
            fig.savefig(fileName_img, bbox_inches='tight', pad_inches = 0.0)         
        if svg == 1:
            ext = 'svg'                     
            fileName_img = SaveFileName+"_PCA_" +str(i+1)+"."+ext
            fig.savefig(fileName_img, bbox_inches='tight', pad_inches = 0.0)
            
                     
    for i in range(10):
     
        pcaspectrum = anlz.eigenvecs[:,i]
        fig = matplotlib.figure.Figure(figsize =(PlotW, PlotH))
        canvas = FigureCanvas(fig)
        fig.add_axes((0.15,0.15,0.75,0.75))
        axes = fig.gca()
        specplot = axes.plot(stk.ev, pcaspectrum)    
        axes.set_xlabel('Photon Energy [eV]')
        axes.set_ylabel('Optical Density')
        if png == 1:
            ext = 'png'     
            fileName_spec = SaveFileName+"_PCAspectrum_" +str(i+1)+"."+ext
            fig.savefig(fileName_spec)
        if pdf == 1:
            ext = 'pdf'     
            fileName_spec = SaveFileName+"_PCAspectrum_" +str(i+1)+"."+ext
            fig.savefig(fileName_spec)
        if svg == 1:
            ext = 'svg'     
            fileName_spec = SaveFileName+"_PCAspectrum_" +str(i+1)+"."+ext
            fig.savefig(fileName_spec)                 

    for i in range (10):
        pcaspectrum = anlz.eigenvecs[:,i]
        fileName_spec = SaveFileName+"_PCAspectrum_" +str(i+1)+".csv"
        cname = "PCAspectrum_" +str(i+1)
        stk.write_csv(fileName_spec, stk.ev, pcaspectrum, cname=cname)
                 
    
    return
Exemple #33
0
def drawmatrix_channels(in_m, channel_names=None, fig=None, x_tick_rot=0,
                        size=None, cmap=plt.cm.RdBu_r, colorbar=True,
                        color_anchor=None, title=None):
    r"""Creates a lower-triangle of the matrix of an nxn set of values. This is
    the typical format to show a symmetrical bivariate quantity (such as
    correlation or coherence between two different ROIs).

    Parameters
    ----------

    in_m: nxn array with values of relationships between two sets of rois or
    channels

    channel_names (optional): list of strings with the labels to be applied to
    the channels in the input. Defaults to '0','1','2', etc.

    fig (optional): a matplotlib figure

    cmap (optional): a matplotlib colormap to be used for displaying the values
    of the connections on the graph

    title (optional): string to title the figure (can be like '$\alpha$')

    color_anchor (optional): determine the mapping from values to colormap
        if None, min and max of colormap correspond to min and max of in_m
        if 0, min and max of colormap correspond to max of abs(in_m)
        if (a,b), min and max of colormap correspond to (a,b)

    Returns
    -------

    fig: a figure object

    """
    N = in_m.shape[0]
    ind = np.arange(N)  # the evenly spaced plot indices

    def channel_formatter(x, pos=None):
        thisind = np.clip(int(x), 0, N - 1)
        return channel_names[thisind]

    if fig is None:
        fig = plt.figure()

    if size is not None:

        fig.set_figwidth(size[0])
        fig.set_figheight(size[1])

    w = fig.get_figwidth()
    h = fig.get_figheight()

    ax_im = fig.add_subplot(1, 1, 1)

    # If you want to draw the colorbar:
    if colorbar:
        divider = make_axes_locatable(ax_im)
        ax_cb = divider.new_vertical(size="10%", pad=0.1, pack_start=True)
        fig.add_axes(ax_cb)

    # Make a copy of the input, so that you don't make changes to the original
    # data provided
    m = in_m.copy()

    # Null the upper triangle, so that you don't get the redundant and the
    # diagonal values:
    idx_null = triu_indices(m.shape[0])
    m[idx_null] = np.nan

    # Extract the minimum and maximum values for scaling of the
    # colormap/colorbar:
    max_val = np.nanmax(m)
    min_val = np.nanmin(m)

    if color_anchor is None:
        color_min = min_val
        color_max = max_val
    elif color_anchor == 0:
        bound = max(abs(max_val), abs(min_val))
        color_min = -bound
        color_max = bound
    else:
        color_min = color_anchor[0]
        color_max = color_anchor[1]

    # The call to imshow produces the matrix plot:
    im = ax_im.imshow(m, origin='upper', interpolation='nearest',
                      vmin=color_min, vmax=color_max, cmap=cmap)

    # Formatting:
    ax = ax_im
    ax.grid(True)
    # Label each of the cells with the row and the column:
    if channel_names is not None:
        for i in range(0, m.shape[0]):
            if i < (m.shape[0] - 1):
                ax.text(i - 0.3, i, channel_names[i], rotation=x_tick_rot)
            if i > 0:
                ax.text(-1, i + 0.3, channel_names[i],
                        horizontalalignment='right')

        ax.set_axis_off()
        ax.set_xticks(np.arange(N))
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(channel_formatter))
        fig.autofmt_xdate(rotation=x_tick_rot)
        ax.set_yticks(np.arange(N))
        ax.set_yticklabels(channel_names)
        ax.set_ybound([-0.5, N - 0.5])
        ax.set_xbound([-0.5, N - 1.5])

    # Make the tick-marks invisible:
    for line in ax.xaxis.get_ticklines():
        line.set_markeredgewidth(0)

    for line in ax.yaxis.get_ticklines():
        line.set_markeredgewidth(0)

    ax.set_axis_off()

    if title is not None:
        ax.set_title(title)

    # The following produces the colorbar and sets the ticks
    if colorbar:
        # Set the ticks - if 0 is in the interval of values, set that, as well
        # as the maximal and minimal values:
        if min_val < 0:
            ticks = [color_min, min_val, 0, max_val, color_max]
        # Otherwise - only set the minimal and maximal value:
        else:
            ticks = [color_min, min_val, max_val, color_max]

        # This makes the colorbar:
        cb = fig.colorbar(im, cax=ax_cb, orientation='horizontal',
                          cmap=cmap,
                          norm=im.norm,
                          boundaries=np.linspace(color_min, color_max, 256),
                          ticks=ticks,
                          format='%.2f')

    # Set the current figure active axis to be the top-one, which is the one
    # most likely to be operated on by users later on
    fig.sca(ax)

    return fig
Exemple #34
0
def drawmatrix_channels(in_m,
                        channel_names=None,
                        fig=None,
                        x_tick_rot=0,
                        size=None,
                        cmap=pl.cm.RdBu_r,
                        colorbar=True,
                        color_anchor=None,
                        title=None):
    r"""Creates a lower-triangle of the matrix of an nxn set of values. This is
    the typical format to show a symmetrical bivariate quantity (such as
    correlation or coherence between two different ROIs).

    Parameters
    ----------

    in_m: nxn array with values of relationships between two sets of rois or
    channels

    channel_names (optional): list of strings with the labels to be applied to
    the channels in the input. Defaults to '0','1','2', etc.

    fig (optional): a matplotlib figure

    cmap (optional): a matplotlib colormap to be used for displaying the values
    of the connections on the graph

    title (optional): string to title the figure (can be like '$\alpha$')

    color_anchor (optional): determine the mapping from values to colormap
        if None, min and max of colormap correspond to min and max of in_m
        if 0, min and max of colormap correspond to max of abs(in_m)
        if (a,b), min and max of colormap correspond to (a,b)

    Returns
    -------

    fig: a figure object

    """
    N = in_m.shape[0]
    ind = np.arange(N)  # the evenly spaced plot indices

    def channel_formatter(x, pos=None):
        thisind = np.clip(int(x), 0, N - 1)
        return channel_names[thisind]

    if fig is None:
        fig = pl.figure()

    if size is not None:

        fig.set_figwidth(size[0])
        fig.set_figheight(size[1])

    w = fig.get_figwidth()
    h = fig.get_figheight()

    ax_im = fig.add_subplot(1, 1, 1)

    #If you want to draw the colorbar:
    if colorbar:
        divider = make_axes_locatable(ax_im)
        ax_cb = divider.new_vertical(size="10%", pad=0.1, pack_start=True)
        fig.add_axes(ax_cb)

    #Make a copy of the input, so that you don't make changes to the original
    #data provided
    m = in_m.copy()

    #Null the upper triangle, so that you don't get the redundant and the
    #diagonal values:
    idx_null = triu_indices(m.shape[0])
    m[idx_null] = np.nan

    #Extract the minimum and maximum values for scaling of the
    #colormap/colorbar:
    max_val = np.nanmax(m)
    min_val = np.nanmin(m)

    if color_anchor is None:
        color_min = min_val
        color_max = max_val
    elif color_anchor == 0:
        bound = max(abs(max_val), abs(min_val))
        color_min = -bound
        color_max = bound
    else:
        color_min = color_anchor[0]
        color_max = color_anchor[1]

    #The call to imshow produces the matrix plot:
    im = ax_im.imshow(m,
                      origin='upper',
                      interpolation='nearest',
                      vmin=color_min,
                      vmax=color_max,
                      cmap=cmap)

    #Formatting:
    ax = ax_im
    ax.grid(True)
    #Label each of the cells with the row and the column:
    if channel_names is not None:
        for i in range(0, m.shape[0]):
            if i < (m.shape[0] - 1):
                ax.text(i - 0.3, i, channel_names[i], rotation=x_tick_rot)
            if i > 0:
                ax.text(-1,
                        i + 0.3,
                        channel_names[i],
                        horizontalalignment='right')

        ax.set_axis_off()
        ax.set_xticks(np.arange(N))
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(channel_formatter))
        fig.autofmt_xdate(rotation=x_tick_rot)
        ax.set_yticks(np.arange(N))
        ax.set_yticklabels(channel_names)
        ax.set_ybound([-0.5, N - 0.5])
        ax.set_xbound([-0.5, N - 1.5])

    #Make the tick-marks invisible:
    for line in ax.xaxis.get_ticklines():
        line.set_markeredgewidth(0)

    for line in ax.yaxis.get_ticklines():
        line.set_markeredgewidth(0)

    ax.set_axis_off()

    if title is not None:
        ax.set_title(title)

    #The following produces the colorbar and sets the ticks
    if colorbar:
        #Set the ticks - if 0 is in the interval of values, set that, as well
        #as the maximal and minimal values:
        if min_val < 0:
            ticks = [color_min, min_val, 0, max_val, color_max]
        #Otherwise - only set the minimal and maximal value:
        else:
            ticks = [color_min, min_val, max_val, color_max]

        #This makes the colorbar:
        cb = fig.colorbar(im,
                          cax=ax_cb,
                          orientation='horizontal',
                          cmap=cmap,
                          norm=im.norm,
                          boundaries=np.linspace(color_min, color_max, 256),
                          ticks=ticks,
                          format='%.2f')

    # Set the current figure active axis to be the top-one, which is the one
    # most likely to be operated on by users later on
    fig.sca(ax)

    return fig
Exemple #35
0
def plot_ica_components(ica, picks=None, ch_type='mag', res=64,
                        layout=None, vmin=None, vmax=None, cmap='RdBu_r',
                        sensors=True, colorbar=False, title=None,
                        show=True, outlines='head', contours=6,
                        image_interp='bilinear'):
    """Project unmixing matrix on interpolated sensor topogrpahy.

    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    picks : int | array-like | None
        The indices of the sources to be plotted.
        If None all are plotted in batches of 20.
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'
        The channel type to plot. For 'grad', the gradiometers are
        collected in pairs and the RMS for each pair is plotted.
    layout : None | Layout
        Layout instance specifying sensor positions (does not need to
        be specified for Neuromag data). If possible, the correct layout is
        inferred from the data.
    vmin : float | callable
        The value specfying the lower bound of the color range.
        If None, and vmax is None, -vmax is used. Else np.min(data).
        If callable, the output equals vmin(data).
    vmax : float | callable
        The value specfying the upper bound of the color range.
        If None, the maximum absolute value is used. If vmin is None,
        but vmax is not, defaults to np.min(data).
        If callable, the output equals vmax(data).
    cmap : matplotlib colormap
        Colormap.
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib
        plot format string (e.g., 'r+' for red plusses). If True, a circle
        will be used (via .add_artist). Defaults to True.
    colorbar : bool
        Plot a colorbar.
    res : int
        The resolution of the topomap image (n pixels along each side).
    show : bool
        Call pyplot.show() at the end.
    outlines : 'head' | dict | None
            The outlines to be drawn. If 'head', a head scheme will be drawn.
            If dict, each key refers to a tuple of x and y positions. The
            values in 'mask_pos' will serve as image mask. If None,
            nothing will be drawn. defaults to 'head'.
    contours : int | False | None
        The number of contour lines to draw. If 0, no contours will be drawn.
    image_interp : str
        The image interpolation to be used. All matplotlib options are
        accepted.

    Returns
    -------
    fig : instance of matplotlib.pyplot.Figure or list
        The figure object(s).
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid import make_axes_locatable

    if picks is None:  # plot components by sets of 20
        n_components = ica.mixing_matrix_.shape[1]
        p = 20
        figs = []
        for k in range(0, n_components, p):
            picks = range(k, min(k + p, n_components))
            fig = plot_ica_components(ica, picks=picks,
                                      ch_type=ch_type, res=res, layout=layout,
                                      vmax=vmax, cmap=cmap, sensors=sensors,
                                      colorbar=colorbar, title=title,
                                      show=show, outlines=outlines,
                                      contours=contours,
                                      image_interp=image_interp)
            figs.append(fig)
        return figs
    elif np.isscalar(picks):
        picks = [picks]

    data = np.dot(ica.mixing_matrix_[:, picks].T,
                  ica.pca_components_[:ica.n_components_])

    if ica.info is None:
        raise RuntimeError('The ICA\'s measurement info is missing. Please '
                           'fit the ICA or add the corresponding info object.')

    data_picks, pos, merge_grads, names, _ = _prepare_topo_plot(ica, ch_type,
                                                                layout)
    pos, outlines = _check_outlines(pos, outlines)
    if outlines not in (None, 'head'):
        image_mask, pos = _make_image_mask(outlines, pos, res)
    else:
        image_mask = None

    data = np.atleast_2d(data)
    data = data[:, data_picks]

    # prepare data for iteration
    fig, axes = _prepare_trellis(len(data), max_col=5)
    if title is None:
        title = 'ICA components'
    fig.suptitle(title)

    if merge_grads:
        from ..channels.layout  import _merge_grad_data
    for ii, data_, ax in zip(picks, data, axes):
        ax.set_title('IC #%03d' % ii, fontsize=12)
        data_ = _merge_grad_data(data_) if merge_grads else data_
        vmin_, vmax_ = _setup_vmin_vmax(data_, vmin, vmax)
        im = plot_topomap(data_.flatten(), pos, vmin=vmin_, vmax=vmax_,
                          res=res, axis=ax, cmap=cmap, outlines=outlines,
                          image_mask=image_mask, contours=contours,
                          image_interp=image_interp)[0]
        if colorbar:
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap)
            cbar.ax.tick_params(labelsize=12)
            cbar.set_ticks((vmin_, vmax_))
            cbar.ax.set_title('AU', fontsize=10)
        ax.set_yticks([])
        ax.set_xticks([])
        ax.set_frame_on(False)
    tight_layout(fig=fig)
    fig.subplots_adjust(top=0.95)
    fig.canvas.draw()

    if show is True:
        plt.show()
    return fig
Exemple #36
0
def plot(net, n, p):

    classname = net.__class__.__name__

    axes.set_xticks([])
    axes.set_yticks([])
    divider = make_axes_locatable(axes)
    subaxes = divider.new_vertical(1.0, pad=0.4, sharex=axes)
    fig.add_axes(subaxes)
    subaxes.set_xticks([])
    subaxes.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
    subaxes.yaxis.set_ticks_position('right')
    subaxes.set_ylabel('Distortion')
    subaxes.set_xlabel('Time')

    Y = net.distortion[::1]
    X = np.arange(len(Y))/float(len(Y)-1)
    subaxes.plot(X,Y)

    if classname == 'NG':
        plt.title('Neural Gas', fontsize=20)
    elif classname == 'SOM':
        plt.title('Self-Organizing Map', fontsize=20)
    elif classname == 'DSOM':
        plt.title('Dynamic Self-Organizing Map', fontsize=20)

    axes.axis([0,1,0,1])
    axes.set_aspect(1)

    bounds = divider.locate(0,0).bounds
    grid = AxesGrid(fig, bounds, nrows_ncols = (n,n), axes_pad = 0.05, label_mode = "1")
    for row in range(n):
        for col in range(n):
            index = row*n+col
            Z = net.codebook[row,col].reshape(p,p) 
            im = grid[index].imshow(Z, interpolation = 'nearest', vmin=0, vmax=1, cmap=plt.cm.gray)
            grid[index].set_yticks([])
            grid[index].set_xticks([])

    classname = net.__class__.__name__
    if classname == 'NG':
        axes.text(0.5, -0.01,
                  r'$\lambda_i = %.3f,\lambda_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
    if classname == 'SOM':
        axes.text(0.5, -0.01,
                  r'$\sigma_i = %.3f,\sigma_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
    elif classname == 'DSOM':
        axes.text(0.5, -0.01,
                  r'$elasticity = %.2f$, $\varepsilon = %.3f$' % (net.elasticity, net.lrate),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
def Scatter_hist(data1, data2, data1b=False, data2b=False, xbinwidth = 0.5, 
                 ybinwidth=0.5, SSE=None, SSEb=None, vmax=1000., colormaps=cm.YlOrBr,
                 cleanstyle = False, roodlichter=0.5, *args,  **kwargs):
    '''
    Three-parts plot with the two parameter sitdirbutions plotted on the sides
    
    Parameters
    -----------
    data1: ndarray
        dataset 1 for x-axis
    data2: ndarray
        dataset 2 for y-axis
    data1b: ndarray
        dataset to plot along the data 1 set
    data2b: ndarray
        dataset to plot along the data 2 set
    binwidth: float
        defines the width of the bins relative to the data used
    cleanstyle: bool True|False
        if True, a more minimalistic version of the plot is given
    *args,  **kwargs: args
        arguments given toi the scatter plot
        example: s=15, marker='o', edgecolors= 'k',facecolor = 'white'

    Returns
    ---------
    fig: matplotlib.figure.Figure object
        the resulting figure
    axScatter: matplotlib.axes.AxesSubplot object
        the scatter plot with the datapoints, can be used to add labels or 
        change the current ticks settings
    axHistx: matplotlib.axes.AxesSubplot object
        the x-axis histogram
    axHisty: matplotlib.axes.AxesSubplot object
        the y-axis histogram
    
    Examples
    ----------
    >>> nMC = 1000
    >>> parval1 = np.random.gamma(5.5,size=nMC)   
    >>> parval2 = np.random.gamma(8.0,size=nMC)   
    >>> parnames = ['par1','par2']
    >>> fig,axScatter,axHistx,axHisty = Scatter_hist(parval1,parval2, 
                                                 cleanstyle = True, s=48, 
                                                 marker='o', edgecolors= 'k', 
                                                 facecolor = 'none',alpha=0.7)    
    >>> parval1b = np.random.uniform(low=0.0, high=30.0,size=nMC)   
    >>> parval2b = np.random.uniform(low=0.0, high=30.0,size=nMC)   
    >>> fig,axScatter,axHistx,axHisty = Scatter_hist(parval1,parval2,parval1b, 
                                                 parval2b, cleanstyle = True, 
                                                 s=48, marker='o', 
                                                 edgecolors= 'k', 
                                                 facecolor = 'none',
                                                 alpha=0.7)
    
    Notes
    ------
    Typical application is to check the dependency of two posterior 
    parameter distrbutions, eventually compared with their selected posteriors
    
    If a second dataset is added to compare, the style options of the scatter
    plot are fixed and the *args, **kwargs have no influence
    
    '''
    if not isinstance(data1, np.ndarray):
        raise Exception('dataset 1 need to be numpy ndarray')
    if not isinstance(data2, np.ndarray):
        raise Exception('dataset 2 need to be numpy ndarray')        
        
    if isinstance(data1b, np.ndarray):
        if not isinstance(data2b, np.ndarray):
            raise Exception('Always combine the data of both')
    if isinstance(data2b, np.ndarray):
        if not isinstance(data1b, np.ndarray):
            raise Exception('Always combine the data of both')

    fig = plt.figure(figsize=(10,10))
    axScatter = plt.subplot(111)
    divider = make_axes_locatable(axScatter)
    #axScatter.set_aspect('equal')
    axScatter.set_autoscale_on(True)

    # create a new axes with  above the axScatter
    axHistx = divider.new_vertical(1.5, pad=0.0001, sharex=axScatter)

    # create a new axes on the right side of the
    # axScatter
    axHisty = divider.new_horizontal(1.5, pad=0.0001, sharey=axScatter)

    fig.add_axes(axHistx)
    fig.add_axes(axHisty)

    # now determine nice limits by hand:
#    binwidth = binwidth
    xmin = np.min(data1)
    xmax = np.max(data1)
    ymin = np.min(data2)
    ymax = np.max(data2)
    #xymax = np.max( [np.max(np.fabs(data1)), np.max(np.fabs(data2))] )
    #lim = (int(xymax/binwidth) + 1) * binwidth

    binsx = np.arange(xmin, xmax + xbinwidth, xbinwidth)
    binsy = np.arange(ymin, ymax + ybinwidth, ybinwidth)
    #bins = np.arange(-lim, lim + binwidth, binwidth)
    
    # the scatter plot:  
    if isinstance(data1b, np.ndarray): #TWO DATA ENTRIES
        if SSE == None:
            print '*args, **kwargs do not have any influcence when using two\
            options'
            axScatter.scatter(data1, data2, facecolor = 'none', 
                              edgecolor='k',s=25)
            axScatter.scatter(data1b, data2b, facecolor='none', 
                              edgecolor='grey',s=25)  

            xminb = np.min(data1b)
            xmaxb = np.max(data1b)
            yminb = np.min(data2b)
            ymaxb = np.max(data2b)   
            binsxb = np.arange(xminb, xmaxb + xbinwidth, xbinwidth)
            binsyb = np.arange(yminb, ymaxb + ybinwidth, ybinwidth)
    
            axHistx.hist(data1b, bins=binsxb, edgecolor='None', 
                         color='grey',normed=True)
            axHisty.hist(data2b, bins=binsyb, orientation='horizontal',  
                         edgecolor='None', color='grey', normed=True) 
    
            axHistx.hist(data1, bins=binsx, edgecolor='None', 
                         color='k', normed=True)
            axHisty.hist(data2, bins=binsy, orientation='horizontal',  
                         edgecolor='None', color='k', normed=True)
        else:                     
            print '*args, **kwargs do not have any influcence when using two\
            options'
            sc1 = axScatter.scatter(data1b, data2b, c=SSEb, vmax=vmax,alpha=roodlichter,
                              edgecolors= 'none', cmap = colormaps, *args,  **kwargs) 
                              
            axScatter.scatter(data1, data2, c=SSE, vmax=vmax, 
                              edgecolors= 'none', cmap = colormaps, *args,  **kwargs)
 

            xminb = np.min(data1b)
            xmaxb = np.max(data1b)
            yminb = np.min(data2b)
            ymaxb = np.max(data2b)   
            binsxb = np.arange(xminb, xmaxb + xbinwidth, xbinwidth)
            binsyb = np.arange(yminb, ymaxb + ybinwidth, ybinwidth)
    
            axHistx.hist(data1b, bins=binsxb, edgecolor='None', 
                         color=colormaps(1.),normed=True)
            axHisty.hist(data2b, bins=binsyb, orientation='horizontal', color=colormaps(1.),
                         edgecolor='None', normed=True) 
    
            axHistx.hist(data1, bins=binsx, edgecolor='None', 
                         color=colormaps(0.), normed=True)
            axHisty.hist(data2, bins=binsy, orientation='horizontal',  
                         edgecolor='None', color=colormaps(0.), normed=True)  
                                     
    else:  #ONLY ONE DATA1 and DATA2
        if SSE == None:
            axScatter.scatter(data1, data2, c= 'black', *args,  **kwargs)                        
            axHistx.hist(data1, bins=binsx, edgecolor='None', color='k')
            axHisty.hist(data2, bins=binsy, orientation='horizontal',  
                         edgecolor='None', color='k')            
        else:
            axScatter.scatter(data1, data2, c=SSE, vmax=vmax, 
                              edgecolors= 'none', cmap = colormaps, *args,  **kwargs)            
            axHistx.hist(data1, bins=binsx, edgecolor='None', color='k')
            axHisty.hist(data2, bins=binsy, orientation='horizontal',  
                         edgecolor='None', color='k')

    # the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
    # thus there is no need to manually adjust the xlim and ylim of these
    # axis.

    majloc1 = MaxNLocator(nbins=4, prune='lower')   
    axScatter.yaxis.set_major_locator(majloc1)   
    majloc2 = MaxNLocator(nbins=4)  
    axScatter.xaxis.set_major_locator(majloc2) 

    axScatter.grid(linestyle = 'dashed', color = '0.75',linewidth = 1.)    
    axScatter.set_axisbelow(True)
    axHisty.set_axisbelow(True)
    axHistx.set_axisbelow(True)
    
    # The 'clean' environment
    if cleanstyle == True:
        plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
                 visible=False)   
        plt.setp(axHistx.get_yticklabels() + axHisty.get_xticklabels(),
                 visible=False)             
        axHisty.set_xticks([])
        axHistx.set_yticks([])
        axHistx.xaxis.set_ticks_position('bottom')
        axHisty.yaxis.set_ticks_position('left')
    
        axHisty.spines['right'].set_color('none')
        axHisty.spines['top'].set_color('none')
        axHisty.spines['bottom'].set_color('none')    
        axHisty.spines['left'].set_color('none') 
        
        axHistx.spines['top'].set_color('none')
        axHistx.spines['right'].set_color('none')
        axHistx.spines['left'].set_color('none') 
        axHistx.spines['bottom'].set_color('none') 
        axScatter.spines['top'].set_color('none') 
        axScatter.spines['right'].set_color('none') 
    else:
        plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
                 visible=False)      
        for tl in axHisty.get_yticklabels():
            tl.set_visible(False)
        for tlp in axHisty.get_xticklabels():
            tlp.set_rotation(-90)
            
        majloc3 = MaxNLocator(nbins=4, prune='lower')   
        axHistx.yaxis.set_major_locator(majloc3)  
        axHistx.yaxis.tick_right()
        majloc4 = MaxNLocator(nbins=4, prune='lower')   
        axHisty.xaxis.set_major_locator(majloc4) 
        axHisty.xaxis.tick_top()

        axHisty.yaxis.grid(linestyle = 'dashed', color = '0.75',linewidth = 1.)
        axHistx.xaxis.grid(linestyle = 'dashed', color = '0.75',linewidth = 1.)
        
    return fig,axScatter,axHistx,axHisty
Exemple #38
0
def plot_ica_components(ica,
                        picks=None,
                        ch_type='mag',
                        res=64,
                        layout=None,
                        vmin=None,
                        vmax=None,
                        cmap='RdBu_r',
                        sensors=True,
                        colorbar=False,
                        title=None,
                        show=True,
                        outlines='head',
                        contours=6,
                        image_interp='bilinear'):
    """Project unmixing matrix on interpolated sensor topogrpahy.

    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    picks : int | array-like | None
        The indices of the sources to be plotted.
        If None all are plotted in batches of 20.
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'
        The channel type to plot. For 'grad', the gradiometers are
        collected in pairs and the RMS for each pair is plotted.
    layout : None | Layout
        Layout instance specifying sensor positions (does not need to
        be specified for Neuromag data). If possible, the correct layout is
        inferred from the data.
    vmin : float | callable
        The value specfying the lower bound of the color range.
        If None, and vmax is None, -vmax is used. Else np.min(data).
        If callable, the output equals vmin(data).
    vmax : float | callable
        The value specfying the upper bound of the color range.
        If None, the maximum absolute value is used. If vmin is None,
        but vmax is not, defaults to np.min(data).
        If callable, the output equals vmax(data).
    cmap : matplotlib colormap
        Colormap.
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib
        plot format string (e.g., 'r+' for red plusses). If True, a circle
        will be used (via .add_artist). Defaults to True.
    colorbar : bool
        Plot a colorbar.
    res : int
        The resolution of the topomap image (n pixels along each side).
    show : bool
        Call pyplot.show() at the end.
    outlines : 'head' | dict | None
            The outlines to be drawn. If 'head', a head scheme will be drawn.
            If dict, each key refers to a tuple of x and y positions. The
            values in 'mask_pos' will serve as image mask. If None,
            nothing will be drawn. defaults to 'head'.
    contours : int | False | None
        The number of contour lines to draw. If 0, no contours will be drawn.
    image_interp : str
        The image interpolation to be used. All matplotlib options are
        accepted.

    Returns
    -------
    fig : instance of matplotlib.pyplot.Figure or list
        The figure object(s).
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid import make_axes_locatable

    if picks is None:  # plot components by sets of 20
        n_components = ica.mixing_matrix_.shape[1]
        p = 20
        figs = []
        for k in range(0, n_components, p):
            picks = range(k, min(k + p, n_components))
            fig = plot_ica_components(ica,
                                      picks=picks,
                                      ch_type=ch_type,
                                      res=res,
                                      layout=layout,
                                      vmax=vmax,
                                      cmap=cmap,
                                      sensors=sensors,
                                      colorbar=colorbar,
                                      title=title,
                                      show=show,
                                      outlines=outlines,
                                      contours=contours,
                                      image_interp=image_interp)
            figs.append(fig)
        return figs
    elif np.isscalar(picks):
        picks = [picks]

    data = np.dot(ica.mixing_matrix_[:, picks].T,
                  ica.pca_components_[:ica.n_components_])

    if ica.info is None:
        raise RuntimeError('The ICA\'s measurement info is missing. Please '
                           'fit the ICA or add the corresponding info object.')

    data_picks, pos, merge_grads, names, _ = _prepare_topo_plot(
        ica, ch_type, layout)
    pos, outlines = _check_outlines(pos, outlines)
    if outlines not in (None, 'head'):
        image_mask, pos = _make_image_mask(outlines, pos, res)
    else:
        image_mask = None

    data = np.atleast_2d(data)
    data = data[:, data_picks]

    # prepare data for iteration
    fig, axes = _prepare_trellis(len(data), max_col=5)
    if title is None:
        title = 'ICA components'
    fig.suptitle(title)

    if merge_grads:
        from ..channels.layout import _merge_grad_data
    for ii, data_, ax in zip(picks, data, axes):
        ax.set_title('IC #%03d' % ii, fontsize=12)
        data_ = _merge_grad_data(data_) if merge_grads else data_
        vmin_, vmax_ = _setup_vmin_vmax(data_, vmin, vmax)
        im = plot_topomap(data_.flatten(),
                          pos,
                          vmin=vmin_,
                          vmax=vmax_,
                          res=res,
                          axis=ax,
                          cmap=cmap,
                          outlines=outlines,
                          image_mask=image_mask,
                          contours=contours,
                          image_interp=image_interp)[0]
        if colorbar:
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap)
            cbar.ax.tick_params(labelsize=12)
            cbar.set_ticks((vmin_, vmax_))
            cbar.ax.set_title('AU', fontsize=10)
        ax.set_yticks([])
        ax.set_xticks([])
        ax.set_frame_on(False)
    tight_layout(fig=fig)
    fig.subplots_adjust(top=0.95)
    fig.canvas.draw()

    if show is True:
        plt.show()
    return fig
Exemple #39
0
def plot_tfr_topomap(tfr,
                     tmin=None,
                     tmax=None,
                     fmin=None,
                     fmax=None,
                     ch_type='mag',
                     baseline=None,
                     mode='mean',
                     layout=None,
                     vmax=None,
                     vmin=None,
                     cmap='RdBu_r',
                     sensors=True,
                     colorbar=True,
                     unit=None,
                     res=64,
                     size=2,
                     format='%1.1e',
                     show_names=False,
                     title=None,
                     axes=None,
                     show=True):
    """Plot topographic maps of specific time-frequency intervals of TFR data

    Parameters
    ----------
    tfr : AvereageTFR
        The AvereageTFR object.
    tmin : None | float
        The first time instant to display. If None the first time point
        available is used.
    tmax : None | float
        The last time instant to display. If None the last time point
        available is used.
    fmin : None | float
        The first frequency to display. If None the first frequency
        available is used.
    fmax : None | float
        The last frequency to display. If None the last frequency
        available is used.
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'
        The channel type to plot. For 'grad', the gradiometers are
        collected in pairs and the RMS for each pair is plotted.
    baseline : tuple or list of length 2
        The time interval to apply rescaling / baseline correction.
        If None do not apply it. If baseline is (a, b)
        the interval is between "a (s)" and "b (s)".
        If a is None the beginning of the data is used
        and if b is None then b is set to the end of the interval.
        If baseline is equal to (None, None) all the time
        interval is used.
    mode : 'logratio' | 'ratio' | 'zscore' | 'mean' | 'percent'
        Do baseline correction with ratio (power is divided by mean
        power during baseline) or z-score (power is divided by standard
        deviation of power during baseline after subtracting the mean,
        power = [power - mean(power_baseline)] / std(power_baseline))
        If None, baseline no correction will be performed.
    layout : None | Layout
        Layout instance specifying sensor positions (does not need to
        be specified for Neuromag data). If possible, the correct layout
        file is inferred from the data; if no appropriate layout file
        was found, the layout is automatically generated from the sensor
        locations.
    vmin : float | callable
        The value specfying the lower bound of the color range.
        If None, and vmax is None, -vmax is used. Else np.min(data).
        If callable, the output equals vmin(data).
    vmax : float | callable
        The value specfying the upper bound of the color range.
        If None, the maximum absolute value is used. If vmin is None,
        but vmax is not, defaults to np.min(data).
        If callable, the output equals vmax(data).
    cmap : matplotlib colormap
        Colormap. For magnetometers and eeg defaults to 'RdBu_r', else
        'Reds'.
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib
        plot format string (e.g., 'r+' for red plusses). If True, a circle will
        be used (via .add_artist). Defaults to True.
    colorbar : bool
        Plot a colorbar.
    unit : str | None
        The unit of the channel type used for colorbar labels.
    res : int
        The resolution of the topomap image (n pixels along each side).
    size : float
        Side length per topomap in inches.
    format : str
        String format for colorbar values.
    show_names : bool | callable
        If True, show channel names on top of the map. If a callable is
        passed, channel names will be formatted using the callable; e.g., to
        delete the prefix 'MEG ' from all channel names, pass the function
        lambda x: x.replace('MEG ', ''). If `mask` is not None, only
        significant sensors will be shown.
    title : str | None
        Title. If None (default), no title is displayed.
    axes : instance of Axis | None
        The axes to plot to. If None the axes is defined automatically.
    show : bool
        Call pyplot.show() at the end.

    Returns
    -------
    fig : matplotlib.figure.Figure
        The figure containing the topography.
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable

    picks, pos, merge_grads, names, _ = _prepare_topo_plot(
        tfr, ch_type, layout)
    if not show_names:
        names = None

    data = tfr.data

    if mode is not None and baseline is not None:
        data = rescale(data, tfr.times, baseline, mode, copy=True)

    # crop time
    itmin, itmax = None, None
    idx = np.where(_time_mask(tfr.times, tmin, tmax))[0]
    if tmin is not None:
        itmin = idx[0]
    if tmax is not None:
        itmax = idx[-1] + 1

    # crop freqs
    ifmin, ifmax = None, None
    idx = np.where(_time_mask(tfr.freqs, fmin, fmax))[0]
    if fmin is not None:
        ifmin = idx[0]
    if fmax is not None:
        ifmax = idx[-1] + 1

    data = data[picks, ifmin:ifmax, itmin:itmax]
    data = np.mean(np.mean(data, axis=2), axis=1)[:, np.newaxis]

    if merge_grads:
        from ..channels.layout import _merge_grad_data
        data = _merge_grad_data(data)

    vmin, vmax = _setup_vmin_vmax(data, vmin, vmax)

    if axes is None:
        fig = plt.figure()
        ax = fig.gca()
    else:
        fig = axes.figure
        ax = axes

    ax.set_yticks([])
    ax.set_xticks([])
    ax.set_frame_on(False)

    if title is not None:
        ax.set_title(title)

    im, _ = plot_topomap(data[:, 0],
                         pos,
                         vmin=vmin,
                         vmax=vmax,
                         axis=ax,
                         cmap=cmap,
                         image_interp='bilinear',
                         contours=False,
                         names=names)

    if colorbar:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap)
        cbar.set_ticks((vmin, vmax))
        cbar.ax.tick_params(labelsize=12)
        cbar.ax.set_title('AU')

    if show:
        plt.show()

    return fig
Exemple #40
0
for str in flist:
	str=str.rstrip('\n')
	if str.find('Real') != -1:
		flag=1
	elif flag==1 and str.find('Imag') != -1:
		flag=0
	elif flag==1 and isNum(str):
		x.append(float(str))
	elif flag==0 and isNum(str):
		y.append(float(str))


fig = plt.figure(1, figsize=(10,10), dpi=50)

axScatter = plt.subplot(111)
divider = make_axes_locatable(axScatter)

axScatter.scatter(x, y)
axScatter.set_aspect(1.)

axes = fig.get_axes()[0]
axes.set_xlim((-3, 3))
axes.set_ylim((-3, 3))
axes.set_aspect('auto', adjustable='box')

plt.draw()
plt.show()


os.remove('/tmp/symbols.txt')
os.remove('/tmp/symbols_noise.txt')
Exemple #41
0
	def plot(self, profile, statsResults):
		# *** Check if there is sufficient data to generate the plot
		if len(statsResults.postHocResults.pValues) <= 0:
			self.emptyAxis('No post-hoc test results')
			return

		if len(statsResults.postHocResults.pValues) > 200:
			QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
			reply = QtGui.QMessageBox.question(self, 'Continue?', 'Plots contains ' + str(len(statsResults.postHocResults.pValues)) + ' rows. ' +
																		'It may take several seconds to generate this plot. We recommend filtering the results first.' + 
																		'Do you wish to continue?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			QtGui.QApplication.instance().restoreOverrideCursor()
			if reply == QtGui.QMessageBox.No:
				self.emptyAxis('Too many rows.')	
				return
				
		# *** Set plot properties
		axesColour = str(self.preferences['Axes colour'].name())
		highlightColor = (0.9, 0.9, 0.9)
		
		# Apply p-value filter
		labels = []
		pValues = []
		effectSizes = []
		lowerCIs = []
		upperCIs = []
		if self.bPvalueFilter:
			for i in xrange(0, len(statsResults.postHocResults.labels)):
				# get numeric p-value
				if isinstance(statsResults.postHocResults.pValues[i], str):
					pValueSplit = statsResults.postHocResults.pValues[i].split(' ')
					if pValueSplit[0][0] == '<':
						pValue = float(pValueSplit[1]) - 1e-6
					else:
						pValue = 1.0
				else:
					pValue = statsResults.postHocResults.pValues[i]
			
				# check if p-value should be filtered
				if pValue <= statsResults.postHocResults.alpha:
					labels.append(statsResults.postHocResults.labels[i])
					pValues.append(statsResults.postHocResults.pValues[i])
					effectSizes.append(statsResults.postHocResults.effectSizes[i])
					lowerCIs.append(statsResults.postHocResults.lowerCIs[i])
					upperCIs.append(statsResults.postHocResults.upperCIs[i])
		else:
			labels = list(statsResults.postHocResults.labels)
			pValues = list(statsResults.postHocResults.pValues)
			effectSizes = list(statsResults.postHocResults.effectSizes)
			lowerCIs = list(statsResults.postHocResults.lowerCIs)
			upperCIs = list(statsResults.postHocResults.upperCIs)
			
		if len(labels) == 0:
			self.emptyAxis('No rows above nominal level.')
			return
			
		# *** Determine dominant group for each contrast (i.e., row).
		#  Adjust labels and effect sizes to reflect the dominant group.
		for i in xrange(0, len(effectSizes)):
			labelSplit = labels[i].split(':')
			if effectSizes[i] > 0.0:
				lowerCIs[i] = effectSizes[i] - lowerCIs[i]
				upperCIs[i] = upperCIs[i] - effectSizes[i]
			else:
				labels[i] = labelSplit[1].strip() + ' : ' + labelSplit[0].strip()
				lowerCIs[i] = effectSizes[i] - lowerCIs[i]
				upperCIs[i] = upperCIs[i] - effectSizes[i]
				effectSizes[i] = -effectSizes[i]
				
		# *** Sort data
		data = zip(labels, pValues, effectSizes, lowerCIs, upperCIs)

		if self.sortingField == 'p-values':
			data = sorted(data, key = operator.itemgetter(1), reverse = True)
		elif self.sortingField == 'Effect sizes':
			data = sorted(data, key = operator.itemgetter(2))
		elif self.sortingField == 'Group labels':
			data = sorted(data, key = lambda row: row[0].lower(), reverse = True)

		labels, pValues, effectSizes, lowerCIs, upperCIs = zip(*data)
		labels = list(labels)
		pValues = list(pValues)
		effectSizes = list(effectSizes)
		lowerCIs = list(lowerCIs)
		upperCIs = list(upperCIs)
		
		# *** Make list of which group is dominant in each contrast.
		dominantGroup = {}
		for i in xrange(0, len(effectSizes)):
			labelSplit = labels[i].split(':')
			groupName = labelSplit[0].strip()

			if groupName in dominantGroup:
				dominantGroup[groupName][0].append(effectSizes[i])
				dominantGroup[groupName][1].append(i)
			else:
				dominantGroup[groupName] = [[effectSizes[i]],[i]]

		# *** Create p-value labels
		pValueTitle = 'p-value'
		pValueLabels = []
		for pValue in pValues:
			if isinstance(pValue, str):
				pValueSplit = pValue.split(' ')
				if pValue[0] == '<':
					pValueLabels.append(r'$<$' + pValueSplit[1])
				else:
					pValueLabels.append(r'$\geq$' + pValueSplit[1])
			else:
				pValueLabels.append(statsResults.getPValueStr(pValue))

		# *** Truncate labels
		adjustedLabels = list(labels)
		if self.preferences['Truncate feature names']:
			length = self.preferences['Length of truncated feature names']
			
			for i in xrange(0, len(labels)):
				if len(labels[i]) > length+3:
					adjustedLabels[i] = labels[i][0:length] + '...'
				
		# *** Set figure size
		plotHeight = self.figHeightPerRow*len(adjustedLabels) 
		self.imageWidth = self.figWidth
		self.imageHeight = plotHeight	+ 0.65	 # 0.65 inches for bottom and top labels
		if self.imageWidth > 256 or self.imageHeight > 256:
				QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
				self.emptyAxis()	
				reply = QtGui.QMessageBox.question(self, 'Excessively large plot', 'The resulting plot is too large to display.')
				QtGui.QApplication.instance().restoreOverrideCursor()
				return
		
		self.fig.set_size_inches(self.imageWidth, self.imageHeight)	
				
		# *** Determine width of y-axis labels
		yLabelBounds = self.yLabelExtents(adjustedLabels, 8)
		
		# *** Size plots which comprise the extended errorbar plot
		self.fig.clear()
		
		heightBottomLabels = 0.4	# inches

		spacingBetweenPlots = 0.25	# inches
		widthNumSeqPlot = 1.25	# inches
		if self.bShowBarPlot == False:
			widthNumSeqPlot = 0.0
			spacingBetweenPlots = 0.0
		
		widthPvalueLabels = 0.75	# inches
		if self.bShowPValueLabels == False:
			widthPvalueLabels = 0.1
				 
		yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight 
		heightPlotFigSpace = plotHeight / self.imageHeight
			 
		xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth
		pValueLabelWidthFigSpace =	widthPvalueLabels / self.imageWidth
		widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace
		
		widthErrorBarPlot = widthPlotFigSpace*self.imageWidth - widthNumSeqPlot - spacingBetweenPlots
				
		axInitAxis = self.fig.add_axes([xPlotOffsetFigSpace,yPlotOffsetFigSpace,widthPlotFigSpace,heightPlotFigSpace])
		divider = make_axes_locatable(axInitAxis)
		divider.get_vertical()[0] = Size.Fixed(len(labels)*self.figHeightPerRow)

		self.fig.text(0.0,1.0,self.preferences['Selected multiple group feature'], va='top', ha='left')
		
		if self.bShowBarPlot == True:
			divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot)
			axErrorbar = divider.new_horizontal(widthErrorBarPlot, pad=spacingBetweenPlots, sharey=axInitAxis)
			self.fig.add_axes(axErrorbar)
		else:
			divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot)
			axErrorbar = axInitAxis
				
		# *** Plot of sequences for each subsystem
		if self.bShowBarPlot == True:
			axNumSeq = axInitAxis
			
			# get relative frequency and standard deviation of each contrast
			maxPercentage = 0
			for i in xrange(0, len(labels)):
				splitLabel = labels[i].split(':')
				groupName1 = splitLabel[0].strip()
				groupName2 = splitLabel[1].strip()
				
				colour1 = str(self.preferences['Group colours'][groupName1].name())
				colour2 = str(self.preferences['Group colours'][groupName2].name())

				meanRelFreq1 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName1 + ': mean rel. freq. (%)')
				meanRelFreq2 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName2 + ': mean rel. freq. (%)')
			
				if self.bShowStdDev:
					stdDev1 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName1 + ': std. dev. (%)')
					stdDev2 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName2 + ': std. dev. (%)')
					endCapSize = self.endCapSize
				else:
					stdDev1 = 0
					stdDev2 = 0
					endCapSize = 0
					
				if meanRelFreq1 + stdDev1 > maxPercentage:
					maxPercentage = meanRelFreq1 + stdDev1
					
				if meanRelFreq2 + stdDev2 > maxPercentage:
					maxPercentage = meanRelFreq2 + stdDev2

				axNumSeq.barh(i+0.0, meanRelFreq1, height = 0.3, xerr=stdDev1, color=colour1, ecolor='black', capsize=endCapSize)
				axNumSeq.barh(i-0.3, meanRelFreq2, height = 0.3, xerr=stdDev2, color=colour2, ecolor='black', capsize=endCapSize)
				
			for value in np.arange(-0.5, len(labels)-1, 2):
				axNumSeq.axhspan(value, value+1, facecolor=highlightColor, edgecolor='none', zorder=-1)
			
			axNumSeq.set_xlabel('Mean proportion (%)')
			axNumSeq.set_xticks([0, maxPercentage])
			axNumSeq.set_xlim([0, maxPercentage*1.05])
			maxPercentageStr = '%.1f' % maxPercentage
			axNumSeq.set_xticklabels(['0.0', maxPercentageStr])
			
			axNumSeq.set_yticks(np.arange(len(labels)))
			axNumSeq.set_yticklabels(adjustedLabels)
			axNumSeq.set_ylim([-1, len(labels)])
					
			for a in axNumSeq.yaxis.majorTicks:
				a.tick1On=False
				a.tick2On=False
					
			for a in axNumSeq.xaxis.majorTicks:
				a.tick1On=True
				a.tick2On=False
				
			for line in axNumSeq.yaxis.get_ticklines(): 
				line.set_color(axesColour)
				
			for line in axNumSeq.xaxis.get_ticklines(): 
				line.set_color(axesColour)
					
			for loc, spine in axNumSeq.spines.iteritems():
				if loc in ['left', 'right','top']:
					spine.set_color('none') 
				else:
					spine.set_color(axesColour)
						
		# *** Plot confidence intervals for each subsystem
		lastAxes = axErrorbar
		markerSize = math.sqrt(float(self.markerSize))
		axErrorbar.errorbar(effectSizes, np.arange(len(labels)), xerr=[lowerCIs,upperCIs], fmt='o', ms=markerSize, mfc='black', mec='black', ecolor='black', zorder=10)
		for groupName in dominantGroup:
			colour = str(self.preferences['Group colours'][groupName].name())
			effectSizes = dominantGroup[groupName][0]
			indices = dominantGroup[groupName][1]
			axErrorbar.plot(effectSizes, indices, ls='', marker='o', ms=markerSize, mfc=colour, mec='black', zorder=100)
			
		axErrorbar.vlines(0, -1, len(labels), linestyle='dashed', color=axesColour)
		
		for value in np.arange(-0.5, len(labels)-1, 2):
			axErrorbar.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1)

		ciTitle = ('%.3g' % ((1.0-statsResults.postHocResults.alpha)*100)) + '% confidence intervals'
		axErrorbar.set_title(ciTitle) 
		axErrorbar.set_xlabel('Difference in mean proportions (%)')
		
		if self.bCustomLimits:
			axErrorbar.set_xlim([self.minX, self.maxX])
		else:
			self.minX, self.maxX = axErrorbar.get_xlim()
 
		if self.bShowBarPlot == False:
			axErrorbar.set_yticks(np.arange(len(labels)))
			axErrorbar.set_yticklabels(labels)
			axErrorbar.set_ylim([-1, len(labels)])
		else:
			for label in axErrorbar.get_yticklabels():
				label.set_visible(False)
				
			for a in axErrorbar.yaxis.majorTicks:
				a.set_visible(False)
				
		for a in axErrorbar.xaxis.majorTicks:
			a.tick1On=True
			a.tick2On=False
				
		for a in axErrorbar.yaxis.majorTicks:
			a.tick1On=False
			a.tick2On=False
			
		for line in axErrorbar.yaxis.get_ticklines(): 
			line.set_visible(False)
				
		for line in axErrorbar.xaxis.get_ticklines(): 
			line.set_color(axesColour)

		for loc, spine in axErrorbar.spines.iteritems():
			if loc in ['left','right','top']:
				spine.set_color('none') 
			else:
				spine.set_color(axesColour)
						
		# *** Show p-values on right of last plot
		if self.bShowPValueLabels == True:
			axRight = lastAxes.twinx()
			axRight.set_yticks(np.arange(len(pValueLabels)))
			axRight.set_yticklabels(pValueLabels)
			axRight.set_ylim([-1, len(pValueLabels)])
			axRight.set_ylabel(pValueTitle)
			
			for a in axRight.yaxis.majorTicks:
				a.tick1On=False
				a.tick2On=False
				
			for loc, spine in axRight.spines.iteritems():
				spine.set_color('none') 

		self.updateGeometry()
		self.draw()
        if (num == 0):
            Vortensity0 = Vortensity

        print("Doing geometric transformation to R-theta plane...")
        # create polar-coordinate array
        Vortensity_polar = geometric_transform(Vortensity.T, cartesian2polar, output_shape=(Vortensity.T.shape[0], Vortensity.T.shape[0]),
                                               extra_keywords={'inputshape': Vortensity.T.shape, 'origin': (Vortensity.T.shape[0]/2, Vortensity.T.shape[1]/2)})
        if (num == 0):
            Vortensity0_polar = Vortensity_polar

        ####################################################################
        # plot
        if not (skip_cartesian):

            ax = fig.add_subplot(1, len(dir_array), count_dir)
            divider = make_axes_locatable(ax)

            cmap = cm.get_cmap('jet')
            im = ax.imshow(np.log10(Vortensity/Vortensity0), origin='lower',
                           vmin=min_scale, vmax=max_scale,
                           extent=[rangeX[0], rangeX[1], rangeY[0], rangeY[1]], cmap=cmap)

            xlabel("$x$", fontsize=16)
            ylabel("$y$", fontsize=16)
            ax.set_xlim(rangeX[0], rangeX[1])
            ax.set_ylim(rangeY[0], rangeY[1])

            xticks, yticks = ax.xaxis.get_majorticklocs(), ax.yaxis.get_majorticklocs()
            ax.xaxis.set_ticklabels(['%d' % (xticks[n] - 0.5*BoxX)
                                     for n in range(len(xticks))])
            ax.yaxis.set_ticklabels(['%d' % (yticks[n] - 0.5 * BoxY)
if run_data_for_tutorials:

    # Make moment 0 maps for the tutorial data

    fid_mom0 = fits.open(
        "../../testingdata/Fiducial0_flatrho_0021_00_radmc_moment0.fits")[0]
    des_mom0 = fits.open(
        "../../testingdata/Design4_flatrho_0021_00_radmc_moment0.fits")[0]

    from mpl_toolkits.axes_grid import make_axes_locatable

    ax = plt.subplot(121)
    im1 = plt.imshow(fid_mom0.data / 1000., origin='lower')
    ax.set_title("Fiducial")
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", "5%", pad="3%")
    cb = plt.colorbar(im1, cax=cax)

    ax2 = plt.subplot(122)
    im2 = plt.imshow(des_mom0.data / 1000., origin='lower')
    ax2.set_title("Design")
    divider = make_axes_locatable(ax2)
    cax2 = divider.append_axes("right", "5%", pad="3%")
    cb2 = plt.colorbar(im2, cax=cax2)
    cb2.set_label(r"K km s$^{-1}$")

    plt.tight_layout()

    plt.savefig(osjoin(fig_path, "design_fiducial_moment0.png"))
    plt.close()
Exemple #44
0
def draw_graph(G,
               labels=None,
               node_colors=None,
               node_shapes=None,
               node_scale=1.0,
               edge_style='solid',
               edge_cmap=None,
               colorbar=False,
               vrange=None,
               layout=None,
               title=None,
               font_family='sans-serif',
               font_size=9,
               stretch_factor=1.0,
               edge_alpha=True,
               fig_size=None):
    """Draw a weighted graph with options to visualize link weights.

    The resulting diagram uses the rank of each node as its size, and the
    weight of each link (after discarding thresholded values, see below) as the
    link opacity.

    It maps edge weight to color as well as line opacity and thickness,
    allowing the color part to be hardcoded over a value range (to permit valid
    cross-figure comparisons for different graphs, so the same color
    corresponds to the same link weight even if each graph has a different
    range of weights).  The nodes sizes are proportional to their degree,
    computed as the sum of the weights of all their links.  The layout defaults
    to circular, but any nx layout function can be passed in, as well as a
    statically precomputed layout.

    Parameters
    ----------
    G : weighted graph
      The values must be of the form (v1,v2), with all v2 in [0,1].  v1 are
      used for colors, v2 for thickness/opacity.

    labels : list or dict, optional.
      An indexable object that maps nodes to strings.  If not given, the
      string form of each node is used as a label.  If False, no labels are
      drawn.

    node_colors : list or dict, optional.
      An indexable object that maps nodes to valid matplotlib color specs.  See
      matplotlib's plot() function for details.

    node_shapes : list or dict, optional.
      An indexable object that maps nodes to valid matplotlib shape specs.  See
      matplotlib's scatter() function for details.  If not given, circles are
      used.

    node_scale : float, optional
      A scale factor to globally stretch or shrink all nodes symbols by.

    edge_style : string, optional
      Line style for the edges, defaults to 'solid'.

    edge_cmap : matplotlib colormap, optional.
      A callable that returns valid color specs, like matplotlib colormaps.
      If not given, edges are colored black.

    colorbar : bool
      If true, automatically add a colorbar showing the mapping of graph weight
      values to colors.

    vrange : pair of floats
      If given, this indicates the total range of values that the weights can
      in principle occupy, and is used to set the lower/upper range of the
      colormap.  This allows you to set the range of multiple different figures
      to the same values, even if each individual graph has range variations,
      so that visual color comparisons across figures are valid.

    layout : function or layout dict, optional
      A NetworkX-like layout function or the result of a precomputed layout for
      the given graph.  NetworkX produces layouts as dicts keyed by nodes and
      with (x,y) pairs of coordinates as values, any function that produces
      this kind of output is acceptable.  Defaults to nx.circular_layout.

    title : string, optional.
      If given, title to put on the main plot.

    font_family : string, optional.
      Font family used for the node labels and title.

    font_size : int, optional.
      Font size used for the node labels and title.

    stretch_factor : float, optional
      A global scaling factor to make the graph larger (or smaller if <1).
      This can be used to separate the nodes if they start overlapping.

    edge_alpha: bool, optional
      Whether to weight the transparency of each edge by a factor equivalent to
      its relative weight

    fig_size: list of height by width, the size of the figure (in
    inches). Defaults to [6,6]

    Returns
    -------
    fig
      The matplotlib figure object with the plot.
    """
    if fig_size is None:
        figsize = [6, 6]

    scaler = figsize[0] / 6.
    # For the size of the node symbols
    node_size_base = 1000 * scaler
    node_min_size = 200 * scaler
    default_node_shape = 'o'
    # Default colors if none given
    default_node_color = 'r'
    default_edge_color = 'k'
    # Max edge width
    max_width = 13 * scaler
    min_width = 2 * scaler
    font_family = 'sans-serif'

    # We'll use the nodes a lot, let's make a numpy array of them
    nodes = np.array(sorted(G.nodes()))
    nnod = len(nodes)

    # Build a 'weighted degree' array obtained by adding the (absolute value)
    # of the weights for all edges pointing to each node:
    amat = nx.adj_matrix(G).A  # get a normal array out of it
    degarr = abs(amat).sum(0)  # weights are sums across rows

    # Map the degree to the 0-1 range so we can use it for sizing the nodes.
    try:
        odegree = rescale_arr(degarr, 0, 1)
        # Make an array of node sizes based on node degree
        node_sizes = odegree * node_size_base + node_min_size
    except ZeroDivisionError:
        # All nodes same size
        node_sizes = np.empty(nnod, float)
        node_sizes.fill(0.5 * node_size_base + node_min_size)

    # Adjust node size list.  We square the scale factor because in mpl, node
    # sizes represent area, not linear size, but it's more intuitive for the
    # user to think of linear factors (the overall figure scale factor is also
    # linear).
    node_sizes *= node_scale ** 2

    # Set default node properties
    if node_colors is None:
        node_colors = [default_node_color] * nnod

    if node_shapes is None:
        node_shapes = [default_node_shape] * nnod

    # Set default edge colormap
    if edge_cmap is None:
        # Make an object with the colormap API, that maps all input values to
        # the default color (with proper alhpa)
        edge_cmap = (lambda val, alpha:
                     colors.colorConverter.to_rgba(default_edge_color, alpha))

    # if vrange is None, we set the color range from the values, else the user
    # can specify it

    # e[2] is edge value: edges_iter returns (i,j,data)
    gvals = np.array([e[2]['weight'] for e in G.edges(data=True)])
    gvmin, gvmax = gvals.min(), gvals.max()
    gvrange = gvmax - gvmin
    if vrange is None:
        vrange = gvmin, gvmax
    # Now, construct the normalization for the colormap
    cnorm = mpl.colors.Normalize(vmin=vrange[0], vmax=vrange[1])

    # Create the actual plot where the graph will be displayed
    figsize = np.array(figsize, float)
    figsize *= stretch_factor

    fig = plt.figure(figsize=figsize)
    ax_graph = fig.add_subplot(1, 1, 1)
    fig.sca(ax_graph)

    if layout is None:
        layout = nx.circular_layout
    # Compute positions for all nodes - nx has several algorithms
    if callable(layout):
        pos = layout(G)
    else:
        # The user can also provide a precomputed layout
        pos = layout

    # Draw nodes
    for nod in nodes:
        nx.draw_networkx_nodes(G,
                               pos,
                               nodelist=[nod],
                               node_color=node_colors[nod],
                               node_shape=node_shapes[nod],
                               node_size=node_sizes[nod],
                               edgecolors='k')
    # Draw edges
    if not isinstance(G, nx.DiGraph):
        # Undirected graph, simple lines for edges
        # We need the size of the value range to properly scale colors
        vsize = vrange[1] - vrange[0]
        gvals_normalized = G.metadata['vals_norm']
        for (u, v, y) in G.edges(data=True):
            # The graph value is the weight, and the normalized values are in
            # [0,1], used for thickness/transparency
            alpha = gvals_normalized[u, v]
            # Scale the color choice to the specified vrange, so that
            ecol = (y['weight'] - vrange[0]) / vsize
            #print 'u,v:',u,v,'y:',y,'ecol:',ecol  # dbg

            if edge_alpha:
                fade = alpha
            else:
                fade = 1.0

            edge_color = [tuple(edge_cmap(ecol, fade))]
            #dbg:
            #print u,v,y
            nx.draw_networkx_edges(G,
                                   pos,
                                   edgelist=[(u, v)],
                                   width=min_width + alpha * max_width,
                                   edge_color=edge_color,
                                   style=edge_style)
    else:
        # Directed graph, use arrows.
        # XXX - this is currently broken.
        raise NotImplementedError("arrow drawing currently broken")

        ## for (u,v,x) in G.edges(data=True):
        ##     y,w = x
        ##     draw_arrows(G,pos,edgelist=[(u,v)],
        ##                 edge_color=[w],
        ##                 alpha=w,
        ##                 edge_cmap=edge_cmap,
        ##                 width=w*max_width)

    # Draw labels.  If not given, we use the string form of the nodes.  If
    # labels is False, no labels are drawn.
    if labels is None:
        labels = map(str, nodes)

    if labels:
        lab_idx = list(range(len(labels)))
        labels_dict = dict(zip(lab_idx, labels))
        nx.draw_networkx_labels(G,
                                pos,
                                labels_dict,
                                font_size=font_size,
                                font_family=font_family)

    if title:
        plt.title(title, fontsize=font_size)

    # Turn off x and y axes labels in pylab
    plt.xticks([])
    plt.yticks([])

    # Add a colorbar if requested
    if colorbar:
        divider = make_axes_locatable(ax_graph)
        ax_cb = divider.new_vertical(size="20%", pad=0.2, pack_start=True)
        fig.add_axes(ax_cb)
        cb = mpl.colorbar.ColorbarBase(ax_cb,
                                    cmap=edge_cmap,
                                    norm=cnorm,
                                    #boundaries = np.linspace(min((gvmin,0)),
                                    #                         max((gvmax,0)),
                                    #                         256),
                                    orientation='horizontal',
                                    format='%.2f')

    # Always return the MPL figure object so the user can further manipulate it
    return fig
Exemple #45
0
	def plot(self, profile, statsResults):
		# *** Check if there is sufficient data to generate the plot
		if len(statsResults.postHocResults.pValues) <= 0:
			self.emptyAxis('No post-hoc test results')
			return

		if len(statsResults.postHocResults.pValues) > 200:
			QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
			reply = QtGui.QMessageBox.question(self, 'Continue?', 'Plots contains ' + str(len(statsResults.postHocResults.pValues)) + ' rows. ' +
																		'It may take several seconds to generate this plot. We recommend filtering the results first.' + 
																		'Do you wish to continue?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
			QtGui.QApplication.instance().restoreOverrideCursor()
			if reply == QtGui.QMessageBox.No:
				self.emptyAxis('Too many rows.')	
				return
				
		# *** Set plot properties
		axesColour = str(self.preferences['Axes colour'].name())
		highlightColor = (0.9, 0.9, 0.9)
		
		# Apply p-value filter
		labels = []
		pValues = []
		effectSizes = []
		lowerCIs = []
		upperCIs = []
		if self.bPvalueFilter:
			for i in xrange(0, len(statsResults.postHocResults.labels)):
				# get numeric p-value
				if isinstance(statsResults.postHocResults.pValues[i], str):
					pValueSplit = statsResults.postHocResults.pValues[i].split(' ')
					if pValueSplit[0][0] == '<':
						pValue = float(pValueSplit[1]) - 1e-6
					else:
						pValue = 1.0
				else:
					pValue = statsResults.postHocResults.pValues[i]
			
				# check if p-value should be filtered
				if pValue <= statsResults.postHocResults.alpha:
					labels.append(statsResults.postHocResults.labels[i])
					pValues.append(statsResults.postHocResults.pValues[i])
					effectSizes.append(statsResults.postHocResults.effectSizes[i])
					lowerCIs.append(statsResults.postHocResults.lowerCIs[i])
					upperCIs.append(statsResults.postHocResults.upperCIs[i])
		else:
			labels = list(statsResults.postHocResults.labels)
			pValues = list(statsResults.postHocResults.pValues)
			effectSizes = list(statsResults.postHocResults.effectSizes)
			lowerCIs = list(statsResults.postHocResults.lowerCIs)
			upperCIs = list(statsResults.postHocResults.upperCIs)
			
		if len(labels) == 0:
			self.emptyAxis('No rows above nominal level.')
			return
			
		# *** Determine dominant group for each contrast (i.e., row).
		#  Adjust labels and effect sizes to reflect the dominant group.
		for i in xrange(0, len(effectSizes)):
			labelSplit = labels[i].split(':')
			if effectSizes[i] > 0.0:
				lowerCIs[i] = effectSizes[i] - lowerCIs[i]
				upperCIs[i] = upperCIs[i] - effectSizes[i]
			else:
				labels[i] = labelSplit[1].strip() + ' : ' + labelSplit[0].strip()
				lowerCIs[i] = effectSizes[i] - lowerCIs[i]
				upperCIs[i] = upperCIs[i] - effectSizes[i]
				effectSizes[i] = -effectSizes[i]
				
		# *** Sort data
		data = zip(labels, pValues, effectSizes, lowerCIs, upperCIs)

		if self.sortingField == 'p-values':
			data = sorted(data, key = operator.itemgetter(1), reverse = True)
		elif self.sortingField == 'Effect sizes':
			data = sorted(data, key = operator.itemgetter(2))
		elif self.sortingField == 'Group labels':
			data = sorted(data, key = lambda row: row[0].lower(), reverse = True)

		labels, pValues, effectSizes, lowerCIs, upperCIs = zip(*data)
		labels = list(labels)
		pValues = list(pValues)
		effectSizes = list(effectSizes)
		lowerCIs = list(lowerCIs)
		upperCIs = list(upperCIs)
		
		# *** Make list of which group is dominant in each contrast.
		dominantGroup = {}
		for i in xrange(0, len(effectSizes)):
			labelSplit = labels[i].split(':')
			groupName = labelSplit[0].strip()

			if groupName in dominantGroup:
				dominantGroup[groupName][0].append(effectSizes[i])
				dominantGroup[groupName][1].append(i)
			else:
				dominantGroup[groupName] = [[effectSizes[i]],[i]]

		# *** Create p-value labels
		pValueTitle = 'p-value'
		pValueLabels = []
		for pValue in pValues:
			if isinstance(pValue, str):
				pValueSplit = pValue.split(' ')
				if pValue[0] == '<':
					pValueLabels.append(r'$<$' + pValueSplit[1])
				else:
					pValueLabels.append(r'$\geq$' + pValueSplit[1])
			else:
				pValueLabels.append(statsResults.getPValueStr(pValue))

		# *** Truncate labels
		adjustedLabels = list(labels)
		if self.preferences['Truncate feature names']:
			length = self.preferences['Length of truncated feature names']
			
			for i in xrange(0, len(labels)):
				if len(labels[i]) > length+3:
					adjustedLabels[i] = labels[i][0:length] + '...'
				
		# *** Set figure size
		plotHeight = self.figHeightPerRow*len(adjustedLabels) 
		self.imageWidth = self.figWidth
		self.imageHeight = plotHeight	+ 0.65	 # 0.65 inches for bottom and top labels
		if self.imageWidth > 256 or self.imageHeight > 256:
				QtGui.QApplication.instance().setOverrideCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
				self.emptyAxis()	
				reply = QtGui.QMessageBox.question(self, 'Excessively large plot', 'The resulting plot is too large to display.')
				QtGui.QApplication.instance().restoreOverrideCursor()
				return
		
		self.fig.set_size_inches(self.imageWidth, self.imageHeight)	
				
		# *** Determine width of y-axis labels
		yLabelBounds = self.yLabelExtents(adjustedLabels, 8)
		
		# *** Size plots which comprise the extended errorbar plot
		self.fig.clear()
		
		heightBottomLabels = 0.4	# inches

		spacingBetweenPlots = 0.25	# inches
		widthNumSeqPlot = 1.25	# inches
		if self.bShowBarPlot == False:
			widthNumSeqPlot = 0.0
			spacingBetweenPlots = 0.0
		
		widthPvalueLabels = 0.75	# inches
		if self.bShowPValueLabels == False:
			widthPvalueLabels = 0.1
				 
		yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight 
		heightPlotFigSpace = plotHeight / self.imageHeight
			 
		xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth
		pValueLabelWidthFigSpace =	widthPvalueLabels / self.imageWidth
		widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace
		
		widthErrorBarPlot = widthPlotFigSpace*self.imageWidth - widthNumSeqPlot - spacingBetweenPlots
				
		axInitAxis = self.fig.add_axes([xPlotOffsetFigSpace,yPlotOffsetFigSpace,widthPlotFigSpace,heightPlotFigSpace])
		divider = make_axes_locatable(axInitAxis)
		divider.get_vertical()[0] = Size.Fixed(len(labels)*self.figHeightPerRow)

		self.fig.text(0.0,1.0,self.preferences['Selected multiple group feature'], va='top', ha='left')
		
		if self.bShowBarPlot == True:
			divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot)
			axErrorbar = divider.new_horizontal(widthErrorBarPlot, pad=spacingBetweenPlots, sharey=axInitAxis)
			self.fig.add_axes(axErrorbar)
		else:
			divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot)
			axErrorbar = axInitAxis
				
		# *** Plot of sequences for each subsystem
		if self.bShowBarPlot == True:
			axNumSeq = axInitAxis
			
			# get relative frequency and standard deviation of each contrast
			maxPercentage = 0
			for i in xrange(0, len(labels)):
				splitLabel = labels[i].split(':')
				groupName1 = splitLabel[0].strip()
				groupName2 = splitLabel[1].strip()
				
				colour1 = str(self.preferences['Group colours'][groupName1].name())
				colour2 = str(self.preferences['Group colours'][groupName2].name())

				meanRelFreq1 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName1 + ': mean rel. freq. (%)')
				meanRelFreq2 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName2 + ': mean rel. freq. (%)')
			
				if self.bShowStdDev:
					stdDev1 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName1 + ': std. dev. (%)')
					stdDev2 = statsResults.getDataFromTable(statsResults.postHocResults.feature, groupName2 + ': std. dev. (%)')
					endCapSize = self.endCapSize
				else:
					stdDev1 = 0
					stdDev2 = 0
					endCapSize = 0
					
				if meanRelFreq1 + stdDev1 > maxPercentage:
					maxPercentage = meanRelFreq1 + stdDev1
					
				if meanRelFreq2 + stdDev2 > maxPercentage:
					maxPercentage = meanRelFreq2 + stdDev2

				axNumSeq.barh(i+0.0, meanRelFreq1, height = 0.3, xerr=stdDev1, color=colour1, ecolor='black', capsize=endCapSize)
				axNumSeq.barh(i-0.3, meanRelFreq2, height = 0.3, xerr=stdDev2, color=colour2, ecolor='black', capsize=endCapSize)
				
			for value in np.arange(-0.5, len(labels)-1, 2):
				axNumSeq.axhspan(value, value+1, facecolor=highlightColor, edgecolor='none', zorder=-1)
			
			axNumSeq.set_xlabel('Mean proportion (%)')
			axNumSeq.set_xticks([0, maxPercentage])
			axNumSeq.set_xlim([0, maxPercentage*1.05])
			maxPercentageStr = '%.1f' % maxPercentage
			axNumSeq.set_xticklabels(['0.0', maxPercentageStr])
			
			axNumSeq.set_yticks(np.arange(len(labels)))
			axNumSeq.set_yticklabels(adjustedLabels)
			axNumSeq.set_ylim([-1, len(labels)])
					
			for a in axNumSeq.yaxis.majorTicks:
				a.tick1On=False
				a.tick2On=False
					
			for a in axNumSeq.xaxis.majorTicks:
				a.tick1On=True
				a.tick2On=False
				
			for line in axNumSeq.yaxis.get_ticklines(): 
				line.set_color(axesColour)
				
			for line in axNumSeq.xaxis.get_ticklines(): 
				line.set_color(axesColour)
					
			for loc, spine in axNumSeq.spines.iteritems():
				if loc in ['left', 'right','top']:
					spine.set_color('none') 
				else:
					spine.set_color(axesColour)
						
		# *** Plot confidence intervals for each subsystem
		lastAxes = axErrorbar
		markerSize = math.sqrt(float(self.markerSize))
		axErrorbar.errorbar(effectSizes, np.arange(len(labels)), xerr=[lowerCIs,upperCIs], fmt='o', ms=markerSize, mfc='black', mec='black', ecolor='black', zorder=10)
		for groupName in dominantGroup:
			colour = str(self.preferences['Group colours'][groupName].name())
			effectSizes = dominantGroup[groupName][0]
			indices = dominantGroup[groupName][1]
			axErrorbar.plot(effectSizes, indices, ls='', marker='o', ms=markerSize, mfc=colour, mec='black', zorder=100)
			
		axErrorbar.vlines(0, -1, len(labels), linestyle='dashed', color=axesColour)
		
		for value in np.arange(-0.5, len(labels)-1, 2):
			axErrorbar.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1)

		ciTitle = ('%.3g' % ((1.0-statsResults.postHocResults.alpha)*100)) + '% confidence intervals'
		axErrorbar.set_title(ciTitle) 
		axErrorbar.set_xlabel('Difference in mean proportions (%)')
		
		if self.bCustomLimits:
			axErrorbar.set_xlim([self.minX, self.maxX])
		else:
			self.minX, self.maxX = axErrorbar.get_xlim()
 
		if self.bShowBarPlot == False:
			axErrorbar.set_yticks(np.arange(len(labels)))
			axErrorbar.set_yticklabels(labels)
			axErrorbar.set_ylim([-1, len(labels)])
		else:
			for label in axErrorbar.get_yticklabels():
				label.set_visible(False)
				
			for a in axErrorbar.yaxis.majorTicks:
				a.set_visible(False)
				
		for a in axErrorbar.xaxis.majorTicks:
			a.tick1On=True
			a.tick2On=False
				
		for a in axErrorbar.yaxis.majorTicks:
			a.tick1On=False
			a.tick2On=False
			
		for line in axErrorbar.yaxis.get_ticklines(): 
			line.set_visible(False)
				
		for line in axErrorbar.xaxis.get_ticklines(): 
			line.set_color(axesColour)

		for loc, spine in axErrorbar.spines.iteritems():
			if loc in ['left','right','top']:
				spine.set_color('none') 
			else:
				spine.set_color(axesColour)
						
		# *** Show p-values on right of last plot
		if self.bShowPValueLabels == True:
			axRight = lastAxes.twinx()
			axRight.set_yticks(np.arange(len(pValueLabels)))
			axRight.set_yticklabels(pValueLabels)
			axRight.set_ylim([-1, len(pValueLabels)])
			axRight.set_ylabel(pValueTitle)
			
			for a in axRight.yaxis.majorTicks:
				a.tick1On=False
				a.tick2On=False

		self.updateGeometry()
		self.draw()
Exemple #46
0
def plot_tfr_topomap(tfr, tmin=None, tmax=None, fmin=None, fmax=None,
                     ch_type='mag', baseline=None, mode='mean', layout=None,
                     vmax=None, vmin=None, cmap='RdBu_r', sensors=True,
                     colorbar=True, unit=None, res=64, size=2, format='%1.1e',
                     show_names=False, title=None, axes=None, show=True):
    """Plot topographic maps of specific time-frequency intervals of TFR data

    Parameters
    ----------
    tfr : AvereageTFR
        The AvereageTFR object.
    tmin : None | float
        The first time instant to display. If None the first time point
        available is used.
    tmax : None | float
        The last time instant to display. If None the last time point
        available is used.
    fmin : None | float
        The first frequency to display. If None the first frequency
        available is used.
    fmax : None | float
        The last frequency to display. If None the last frequency
        available is used.
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'
        The channel type to plot. For 'grad', the gradiometers are
        collected in pairs and the RMS for each pair is plotted.
    baseline : tuple or list of length 2
        The time interval to apply rescaling / baseline correction.
        If None do not apply it. If baseline is (a, b)
        the interval is between "a (s)" and "b (s)".
        If a is None the beginning of the data is used
        and if b is None then b is set to the end of the interval.
        If baseline is equal to (None, None) all the time
        interval is used.
    mode : 'logratio' | 'ratio' | 'zscore' | 'mean' | 'percent'
        Do baseline correction with ratio (power is divided by mean
        power during baseline) or z-score (power is divided by standard
        deviation of power during baseline after subtracting the mean,
        power = [power - mean(power_baseline)] / std(power_baseline))
        If None, baseline no correction will be performed.
    layout : None | Layout
        Layout instance specifying sensor positions (does not need to
        be specified for Neuromag data). If possible, the correct layout
        file is inferred from the data; if no appropriate layout file
        was found, the layout is automatically generated from the sensor
        locations.
    vmin : float | callable
        The value specfying the lower bound of the color range.
        If None, and vmax is None, -vmax is used. Else np.min(data).
        If callable, the output equals vmin(data).
    vmax : float | callable
        The value specfying the upper bound of the color range.
        If None, the maximum absolute value is used. If vmin is None,
        but vmax is not, defaults to np.min(data).
        If callable, the output equals vmax(data).
    cmap : matplotlib colormap
        Colormap. For magnetometers and eeg defaults to 'RdBu_r', else
        'Reds'.
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib
        plot format string (e.g., 'r+' for red plusses). If True, a circle will
        be used (via .add_artist). Defaults to True.
    colorbar : bool
        Plot a colorbar.
    unit : str | None
        The unit of the channel type used for colorbar labels.
    res : int
        The resolution of the topomap image (n pixels along each side).
    size : float
        Side length per topomap in inches.
    format : str
        String format for colorbar values.
    show_names : bool | callable
        If True, show channel names on top of the map. If a callable is
        passed, channel names will be formatted using the callable; e.g., to
        delete the prefix 'MEG ' from all channel names, pass the function
        lambda x: x.replace('MEG ', ''). If `mask` is not None, only
        significant sensors will be shown.
    title : str | None
        Title. If None (default), no title is displayed.
    axes : instance of Axis | None
        The axes to plot to. If None the axes is defined automatically.
    show : bool
        Call pyplot.show() at the end.

    Returns
    -------
    fig : matplotlib.figure.Figure
        The figure containing the topography.
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable

    picks, pos, merge_grads, names, _ = _prepare_topo_plot(tfr, ch_type,
                                                           layout)
    if not show_names:
        names = None

    data = tfr.data

    if mode is not None and baseline is not None:
        data = rescale(data, tfr.times, baseline, mode, copy=True)

    # crop time
    itmin, itmax = None, None
    if tmin is not None:
        itmin = np.where(tfr.times >= tmin)[0][0]
    if tmax is not None:
        itmax = np.where(tfr.times <= tmax)[0][-1]

    # crop freqs
    ifmin, ifmax = None, None
    if fmin is not None:
        ifmin = np.where(tfr.freqs >= fmin)[0][0]
    if fmax is not None:
        ifmax = np.where(tfr.freqs <= fmax)[0][-1]

    data = data[picks, ifmin:ifmax, itmin:itmax]
    data = np.mean(np.mean(data, axis=2), axis=1)[:, np.newaxis]

    if merge_grads:
        from ..channels.layout  import _merge_grad_data
        data = _merge_grad_data(data)

    vmin, vmax = _setup_vmin_vmax(data, vmin, vmax)

    if axes is None:
        fig = plt.figure()
        ax = fig.gca()
    else:
        fig = axes.figure
        ax = axes

    ax.set_yticks([])
    ax.set_xticks([])
    ax.set_frame_on(False)

    if title is not None:
        ax.set_title(title)

    im, _ = plot_topomap(data[:, 0], pos, vmin=vmin, vmax=vmax,
                         axis=ax, cmap=cmap, image_interp='bilinear',
                         contours=False, names=names)

    if colorbar:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cbar = plt.colorbar(im, cax=cax, format='%3.2f', cmap=cmap)
        cbar.set_ticks((vmin, vmax))
        cbar.ax.tick_params(labelsize=12)
        cbar.ax.set_title('AU')

    if show:
        plt.show()

    return fig
Exemple #47
0
def coloured_spy(A, cmap_name="coolwarm", log=False, symmetric_colorbar=False, **kwargs):
    """
    Convenience function for using matplotlib to
    generate a spy plot for inspecting e.g. a jacobian
    matrix or its LU decomposition.

    Parameters
    ----------
    A: 2D array
        Array to inspect, populated e.g. by jacobian callback.
    cmap_name: string (default: coolwarm)
        name of matplotlib colormap to use, kwargs["cmap"] overrides this.
    log: bool or int
        when True: LogNorm/SymLogNorm is used,
        when integer: SymlogNorm(10**log). Note that "norm" in kwargs
        override this.
    symmetric_colorbar: bool or float
        to make divergent colormaps pass through zero as intended.
        if float: max abolute value of colormap (linear)

    Returns
    -------
    Pair (tuple) of axes plotted to (spy, colorbar)

    .. note:: colorbar does not play nicely with
            SymLogNorm why a custom colorbar axes is drawn.

    """
    from matplotlib.ticker import MaxNLocator
    from matplotlib.cm import get_cmap
    from matplotlib.colors import LogNorm, SymLogNorm
    from mpl_toolkits.axes_grid import make_axes_locatable

    A = np.asarray(A)
    if "cmap" not in kwargs:
        kwargs["cmap"] = get_cmap(cmap_name)

    plt.figure()
    ax_imshow = plt.subplot(111)

    if log is not False and "norm" not in kwargs:
        if isinstance(symmetric_colorbar, (float, int)) and symmetric_colorbar is not False:
            Amin = -symmetric_colorbar
            Amax = symmetric_colorbar
        else:
            Amin = np.min(A[np.where(A != 0)])
            Amax = np.max(A[np.where(A != 0)])

        if symmetric_colorbar is True:
            Amin = -max(-Amin, Amax)
            Amax = -Amin

        if log is True:
            if np.any(A < 0):
                log = int(np.round(np.log10(Amax) - 13))
            else:
                minlog = int(floor(np.log10(Amin)))
                maxlog = int(ceil(np.log10(Amax)))
                tick_locations = [10 ** x for x in range(minlog, maxlog + 1)]
                kwargs["norm"] = LogNorm()
        elif isinstance(log, int):
            tick_locations = []
            if Amin < 0:
                minlog = int(ceil(np.log10(-Amin)))
                tick_locations.extend([-(10 ** x) for x in range(minlog, log - 1, -1)])
                tick_locations.extend([0])
            else:
                tick_locations.extend([0])
                minlog = int(floor(np.log10(Amin)))
                tick_locations.extend([10 ** x for x in range(minlog, log + 1)])

            if Amax < 0:
                pass  # Ticks already reach 0
            else:
                maxlog = int(ceil(np.log10(Amax)))
                tick_locations.extend([10 ** x for x in range(log, maxlog + 1)])
            kwargs["norm"] = SymLogNorm(10 ** log)
        else:
            raise TypeError("log kwarg not understood: {}".format(log))
    else:
        tick_locations = np.linspace(np.min(A), np.max(A), 10)

    ax_imshow.imshow(A, interpolation="none", **kwargs)
    ya = ax_imshow.get_yaxis()
    ya.set_major_locator(MaxNLocator(integer=True))
    xa = ax_imshow.get_xaxis()
    xa.set_major_locator(MaxNLocator(integer=True))

    divider = make_axes_locatable(ax_imshow)
    ax_colorbar = divider.append_axes("right", size="5%", pad=0.05)

    def colorbar(ticks=None, norm=None, log10threshy=None):
        if isinstance(norm, (LogNorm, SymLogNorm)):
            levels = np.concatenate(
                [np.linspace(ticks[i], ticks[i + 1], 9, endpoint=False) for i in range(len(ticks) - 1)]
                + [np.array([ticks[-1]])]
            ).flatten()
        else:
            levels = ticks
        xc = [np.zeros_like(levels), np.ones_like(levels)]
        yc = [levels, levels]
        ax_colorbar.contourf(xc, yc, yc, levels=levels, norm=norm, cmap=kwargs["cmap"])
        if isinstance(norm, LogNorm):
            ax_colorbar.set_yscale("log")
        elif isinstance(norm, SymLogNorm):
            ax_colorbar.set_yscale("symlog", linthreshy=10 ** log)
        ax_colorbar.yaxis.tick_right()
        ax_colorbar.set_xticks([])
        ax_colorbar.set_yticks(ticks)

    colorbar(ticks=tick_locations, norm=kwargs.get("norm", None))
    plt.tight_layout()
    return ax_imshow, ax_colorbar