def plot_spectrum_with_dos(hlat,
                           ksys_fracM,
                           omegacM,
                           nuM,
                           ngrid,
                           Wfig=90,
                           Hfig=None,
                           x0frac=0.15,
                           y0frac=0.1,
                           wsfrac=0.4,
                           hs=None,
                           wsdosfrac=0.3,
                           vspace=8,
                           hspace=8,
                           tspace=10,
                           FSFS=8,
                           xlabel=None,
                           ylabel=None,
                           title=None):
    """Plot chern spectrum vs ksize (or other variable on x axis), with corresponding DOS plot aligned with y axis
    (increasing in frequency).

    Parameters
    ----------
    hlat : haldane_lattice
    Wfig : int or float
        width of the figure in mm
    Hfig : int or float or None
        Height of the figure in mm
    x0frac : fraction of Wfig to leave blank left of plot
    y0frac : fraction of Wfig to leave blank below plot
    wsfrac : fraction of Wfig to make width of subplot
    hs : height of subplot in mm. If none, uses ws = wsfrac * Wfig
    vspace : vertical space between subplots
    hspace : horizontal space btwn subplots
    tspace : space above top figure
    fontsize : size of text labels, title

    Returns
    -------
    fig : matplotlib.pyplot figure instance
    ax : matplotlib.pyplot axis instance
    """
    # Make figure
    fig, ax = initialize_spectrum_with_dos_plot(Wfig=Wfig,
                                                Hfig=Hfig,
                                                x0frac=x0frac,
                                                y0frac=y0frac,
                                                wsfrac=wsfrac,
                                                hs=hs,
                                                wsdosfrac=wsdosfrac,
                                                vspace=vspace,
                                                hspace=hspace,
                                                tspace=tspace,
                                                fontsize=FSFS)

    # ax[2].xaxis.set_major_locator( MaxNLocator(nbins = 3) ) #, prune = 'lower') )
    # ax[3].xaxis.set_major_locator( MaxNLocator(nbins = 3) )

    # Plot sideways DOS colored by PR: http://matplotlib.org/examples/pylab_examples/scatter_hist.html
    print 'kpfns: adding ipr to axis...'
    hlat.add_ipr_to_ax(ax[0],
                       ipr=None,
                       alpha=1.0,
                       inverse_PR=False,
                       norm=None,
                       nbins=75,
                       fontsize=FSFS,
                       cbar_ax=ax[2],
                       vmin=None,
                       vmax=None,
                       linewidth=0,
                       cax_label=r'$p$',
                       make_cbar=True,
                       climbars=True,
                       cbar_labelpad=3,
                       orientation='horizontal',
                       cbar_orientation='horizontal',
                       invert_xaxis=True,
                       ylabel=r'$D(\omega)$',
                       xlabel='Oscillation frequency $\omega$',
                       cbar_nticks=3,
                       cbar_tickfmt='%0.1f')
    leplt.plot_pcolormesh(ksys_fracM,
                          omegacM,
                          nuM,
                          ngrid,
                          ax=ax[1],
                          cax=ax[3],
                          method='nearest',
                          cmap=cmaps.diverging_cmap(250, 10, l=30),
                          vmin=-1.0,
                          vmax=1.0,
                          title=title,
                          xlabel=xlabel,
                          ylabel=ylabel,
                          cax_label=r'$\nu$',
                          cbar_labelpad=3,
                          cbar_orientation='horizontal',
                          ticks=[-1, 0, 1],
                          fontsize=FSFS)
    # plt.show()
    # sys.exit()

    # Add title
    ax[0].annotate(title,
                   xy=(0.5, .95),
                   xycoords='figure fraction',
                   horizontalalignment='center',
                   verticalalignment='center')
    # Match axes
    ax[0].set_ylim(ax[1].get_ylim())
    ax[0].xaxis.set_major_locator(MaxNLocator(nbins=2))  # , prune = 'upper') )
    ax[1].yaxis.set_label_position("right")
    ax[1].yaxis.set_ticks_position('both')
    plt.setp(ax[1].get_yticklabels(), visible=False)
    ax[2].xaxis.set_label_position("top")
    ax[3].xaxis.set_label_position("top")

    return fig, ax
def plot_chern_spectrum_on_axis(kcoll, ax, dos_ax, cbar_ipr_ax, cbar_nu_ax, fontsize=8, alpha=1.0,
                                ipr_vmin=None, ipr_vmax=None, cbar_labelpad=3, invert_xaxis=True,
                                ipr_cax_label='participation\nratio,' + r' $p$',
                                chern_cax_label='Chern\nnumber, ' + r'$\nu$'):
    """
    Parameters
    ----------
    kcoll : HaldaneCollection instance
        The chern collection to add to the plot
    ax : matplotlib axis instance
        the axis on which to add the spectrum
    dos_ax : matplotlib axis instance
        the axis on which to add
    alpha : float
        opacity of the spectrum and DOS added to the plot

    Returns
    -------
    ax, dos_ax
    """
    dmyi = 0
    for hlat_name in kcoll.cherns:
        # Grab a pointer to the haldane_lattice
        hlat = kcoll.cherns[hlat_name][0].haldane_lattice
        dmyi += 1
    if dmyi > 1:
        raise RuntimeError('This function takes a HaldaneCollection which is allowed only ONE haldane_lattice-- ' +
                           'ie, a chern spectrum for a single haldaneLattice instance')

    print 'Opening hlat_name = ', hlat_name
    ngrid = len(kcoll.cherns[hlat_name][0].chern_finsize)

    # Assume all ksize elements are the same size for now
    ksys_frac = kcoll.cherns[hlat_name][0].chern_finsize[:, -2]*0.5
    ksys_fracM = np.array([ksys_frac for i in range(len(kcoll.cherns[hlat_name]))])

    # Build omegacV
    omegacV = np.zeros(len(kcoll.cherns[hlat_name]))
    nuM = np.zeros((len(kcoll.cherns[hlat_name]), len(ksys_frac)))

    for ind in range(len(kcoll.cherns[hlat_name])):
        print 'ind = ', ind
        cp_ii = kcoll.cherns[hlat_name][ind].cp
        omegacV[ind] = cp_ii['omegac']
        nuM[ind, :] = kcoll.cherns[hlat_name][ind].chern_finsize[:, -1]

    omegacM = omegacV.reshape(len(nuM), 1) * np.ones_like(nuM)
    print 'omegacM = ', omegacM

    print 'kpfns: adding ipr and chern spectrum to axes...'
    print 'Adding chern spectrum to axis: ax = ', ax
    leplt.plot_pcolormesh(ksys_fracM, omegacM, nuM, ngrid, ax=ax, cax=cbar_nu_ax, method='nearest',
                          cmap=cmaps.diverging_cmap(250, 10, l=30),
                          vmin=-1.0, vmax=1.0, title=None, xlabel=None, ylabel=None,  cax_label=chern_cax_label,
                          cbar_labelpad=cbar_labelpad, cbar_orientation='horizontal', ticks=[-1, 0, 1],
                          fontsize=fontsize, alpha=alpha)

    if dos_ax is not None and dos_ax != 'none':
        print 'Adding ipr to DOS axis: dos_ax = ', dos_ax
        hlat.add_ipr_to_ax(dos_ax, ipr=None, alpha=alpha, inverse_PR=False,
                           norm=None, nbins=75, fontsize=fontsize, cbar_ax=cbar_ipr_ax,
                           vmin=ipr_vmin, vmax=ipr_vmax, linewidth=0, cax_label=ipr_cax_label,
                           make_cbar=True, climbars=True,
                           cbar_labelpad=cbar_labelpad, orientation='horizontal', cbar_orientation='horizontal',
                           invert_xaxis=invert_xaxis, ylabel=None, xlabel=None,
                           cbar_nticks=2, cbar_tickfmt='%0.1f')
        ax.set_ylim(dos_ax.get_ylim())

    return ax, dos_ax, cbar_ipr_ax, cbar_nu_ax
def movie_cherns_varyloc(ccoll, title='Chern number calculation for varied positions',
                         filename='chern_varyloc', rootdir=None, exten='.png', max_boxfrac=None, max_boxsize=None,
                         xlabel=None, ylabel=None, step=0.5, fracsteps=False, framerate=3):
    """Plot the chern as a function of space for each haldane_lattice examined

    Parameters
    ----------
    ccoll : ChernCollection instance
        The collection of varyloc chern calcs to make into a movie
    title : str
        title of the movie
    filename : str
        the name of the files to save
    rootdir : str or None
        The cproot directory to use (usually self.cp['rootdir'])
    exten : str (.png, .jpg, etc)
        file type extension
    max_boxfrac : float
        Fraction of spatial extent of the sample to use as maximum bound for kitaev sum
    max_boxsize : float or None
        If None, uses max_boxfrac * spatial extent of the sample asmax_boxsize
    xlabel : str
        label for x axis
    ylabel : str
        label for y axis
    step : float (default=1.0)
        how far apart to sample kregion vertices in varyloc
    fracsteps : bool
    framerate : int
        The framerate at which to save the movie
    max_boxfrac : float
        Fraction of spatial extent of the sample to use as maximum bound for kitaev sum
    max_boxsize : float or None
        If None, uses max_boxfrac * spatial extent of the sample asmax_boxsize
    """
    rad = 1.0
    divgmap = cmaps.diverging_cmap(250, 10, l=30)

    # plot it
    for hlat_name in ccoll.cherns:
        hlat = ccoll.cherns[hlat_name][0].haldane_lattice
        if hlat.lp['shape'] == 'square':
            # get extent of the network from Bounding box
            Radius = np.abs(hlat.lp['BBox'][0, 0])
        else:
            # todo: allow different geometries
            pass

        # Initialize the figure
        h_mm = 90
        w_mm = 120
        # To get space between subplots, figure out how far away ksize region needs to be, based on first chern
        # Compare max ksize to be used with spatial extent of the lattice. If comparable, make hspace large.
        # Otherwise, use defaults
        ksize = ccoll.cherns[hlat_name][0].chern_finsize[:, 2]
        cgll = ccoll.cherns[hlat_name][0].haldane_lattice.lattice
        maxsz = max(np.max(cgll.xy[:, 0]) - np.min(cgll.xy[:, 0]),
                    np.max(cgll.xy[:, 1]) - np.min(cgll.xy[:, 1]))
        if max_boxsize is not None:
            ksize = ksize[ksize < max_boxsize]
        else:
            if max_boxfrac is not None:
                max_boxsize = max_boxfrac * maxsz
                ksize = ksize[ksize < max_boxsize]
            else:
                ksize = ksize
                max_boxsize = np.max(ksize)
        if max_boxsize > 0.9 * maxsz:
            center0_frac = 0.3
            center2_frac = 0.75
        elif max_boxsize > 0.65 * maxsz:
            center0_frac = 0.35
            center2_frac = 0.72
        elif max_boxsize > 0.55 * maxsz:
            center0_frac = 0.375
            center2_frac = 0.71
        else:
            center0_frac = 0.4
            center2_frac = 0.7

        fig, ax = initialize_1p5panelcbar_fig(Wfig=w_mm, Hfig=h_mm, wsfrac=0.4, wssfrac=0.4,
                                              center0_frac=center0_frac, center2_frac=center2_frac)

        # dimensions of video in pixels
        final_h = 720
        final_w = 960
        actual_dpi = final_h / (float(h_mm) / 25.4)

        # Add the network to the figure
        hlat = ccoll.cherns[hlat_name][0].haldane_lattice
        netvis.movie_plot_2D(hlat.lattice.xy, hlat.lattice.BL, 0 * hlat.lattice.BL[:, 0],
                             None, None, ax=ax[0], fig=fig, axcb=None,
                             xlimv='auto', ylimv='auto', climv=0.1, colorz=False, ptcolor=None, figsize='auto',
                             colormap='BlueBlackRed', bgcolor='#ffffff', axis_off=True, axis_equal=True,
                             lw=0.2)

        # Add title
        if title is not None:
            ax[0].annotate(title, xy=(0.5, .95), xycoords='figure fraction',
                           horizontalalignment='center', verticalalignment='center')
        if xlabel is not None:
            ax[0].set_xlabel(xlabel)
        if ylabel is not None:
            ax[0].set_xlabel(ylabel)

        # Position colorbar
        sm = plt.cm.ScalarMappable(cmap=divgmap, norm=plt.Normalize(vmin=-1, vmax=1))
        # fake up the array of the scalar mappable.
        sm._A = []
        cbar = plt.colorbar(sm, cax=ax[1], orientation='horizontal', ticks=[-1, 0, 1])
        ax[1].set_xlabel(r'$\nu$')
        ax[1].xaxis.set_label_position("top")
        ax[2].axis('off')

        # Add patches (rectangles from cherns at each site) to the figure
        print 'Opening hlat_name = ', hlat_name
        done = False
        ind = 0
        while done is False:
            rectps = []
            colorL = []
            for chernii in ccoll.cherns[hlat_name]:
                # Grab small, medium, and large circles
                ksize = chernii.chern_finsize[:, 2]
                if max_boxsize is not None:
                    ksize = ksize[ksize < max_boxsize]
                else:
                    if max_boxfrac is not None:
                        cgll = chernii.haldane_lattice.lattice
                        maxsz = max(np.max(cgll.xy[:, 0]) - np.min(cgll.xy[:, 0]),
                                    np.max(cgll.xy[:, 1]) - np.min(cgll.xy[:, 1]))
                        max_boxsize = max_boxfrac * maxsz
                        ksize = ksize[ksize < max_boxsize]
                    else:
                        ksize = ksize
                        max_boxsize = np.max(ksize)

                # print 'ksize =  ', ksize
                # print 'max_boxsize =  ', max_boxsize

                xx = float(chernii.cp['poly_offset'].split('/')[0])
                yy = float(chernii.cp['poly_offset'].split('/')[1])
                nu = chernii.chern_finsize[:, -1]
                rad = step
                rect = plt.Rectangle((xx-rad*0.5, yy-rad*0.5), rad, rad, ec="none")
                colorL.append(nu[ind])
                rectps.append(rect)

            p = PatchCollection(rectps, cmap=divgmap, alpha=1.0, edgecolors='none')
            p.set_array(np.array(np.array(colorL)))
            p.set_clim([-1., 1.])

            # Add the patches of nu calculations for each site probed
            ax[0].add_collection(p)

            # Draw the kitaev cartoon in second axis with size ksize[ind]
            polygon1, polygon2, polygon3 = kfns.get_kitaev_polygons(ccoll.cp['shape'], ccoll.cp['regalph'],
                                                                    ccoll.cp['regbeta'], ccoll.cp['reggamma'],
                                                                    ksize[ind])
            patchlist = []
            patchlist.append(patches.Polygon(polygon1, color='r'))
            patchlist.append(patches.Polygon(polygon2, color='g'))
            patchlist.append(patches.Polygon(polygon3, color='b'))
            polypatches = PatchCollection(patchlist, cmap=cm.jet, alpha=0.4, zorder=99, linewidths=0.4)
            colors = np.linspace(0, 1, 3)[::-1]
            polypatches.set_array(np.array(colors))
            ax[2].add_collection(polypatches)
            ax[2].set_xlim(ax[0].get_xlim())
            ax[2].set_ylim(ax[0].get_ylim())

            # Save the plot
            # make index string
            indstr = '_{0:06d}'.format(ind)
            hlat_cmesh = kfns.get_cmeshfn(ccoll.cherns[hlat_name][0].haldane_lattice.lp, rootdir=rootdir)
            specstr = '_Nks' + '{0:03d}'.format(len(ksize)) + '_step' + sf.float2pstr(step) \
                      + '_maxbsz' + sf.float2pstr(max_boxsize)
            outdir = hlat_cmesh + '_' + hlat.lp['LatticeTop'] + '_varyloc_stills' + specstr + '/'
            fnout = outdir + filename + specstr + indstr + exten
            print 'saving figure: ' + fnout
            le.ensure_dir(outdir)
            fig.savefig(fnout, dpi=actual_dpi*2)

            # Save at lower res after antialiasing
            f_img = Image.open(fnout)
            f_img.resize((final_w, final_h), Image.ANTIALIAS).save(fnout)

            # clear patches
            p.remove()
            polypatches.remove()
            # del p

            # Update index
            ind += 1
            if ind == len(ksize):
                done = True

        # Turn into movie
        imgname = outdir + filename + specstr
        movname = hlat_cmesh + filename + specstr + '_mov'
        subprocess.call(['./ffmpeg', '-framerate', str(int(framerate)), '-i', imgname + '_%06d' + exten, movname + '.mov',
                         '-vcodec', 'libx264', '-profile:v', 'main', '-crf', '12', '-threads', '0',
                         '-r', '30', '-pix_fmt', 'yuv420p'])
def plot_cherns_varyloc(ccoll, title='Chern number calculation for varied positions',
                        filename='chern_varyloc', exten='.pdf', rootdir=None, outdir=None,
                        max_boxfrac=None, max_boxsize=None,
                        xlabel=None, ylabel=None, step=0.5, fracsteps=False,
                        singleksz_frac=None, singleksz=-1.0, maxchern=False,
                        ax=None, cbar_ax=None, save=True, make_cbar=True, colorz=False,
                        dpi=600, colormap='divgmap_blue_red'):
    """Plot the chern as a function of space for each haldane_lattice examined. If save==True, saves figure to


    Parameters
    ----------
    ccoll : ChernCollection instance
    filename : str
        name of the file to output as the plot
    rootdir : str or None
        if specified, dictates the path where the file is stored, with the output directory as
        outdir = kfns.get_cmeshfn(ccoll.cherns[hlat_name][0].haldane_lattice.lp, rootdir=rootdir)
    max_boxfrac : float
        Fraction of spatial extent of the sample to use as maximum bound for kitaev sum
    max_boxsize : float or None
        If None, uses max_boxfrac * spatial extent of the sample asmax_boxsize
    singleksz : float
        if positive, plots the spatially-resolved chern number for a single kitaev summation region size, closest to
        the supplied value in actual size. Otherwise, draws many rectangles of different sizes for different ksizes.
        If positive, IGNORES max_boxfrac and max_boxsize arguments
    maxchern : bool
        if True, plots the EXTREMAL spatially-resolved chern number for each voxel --> ie the maximum (signed absolute)
        value it reaches. Otherwise, draws many rectangles of different sizes for different ksizes.
        If True, the function IGNORES max_boxfrac and max_boxsize arguments
    ax : axis instance or None
    cbar_ax : axis instance or None
    save : bool
    make_cbar : bool
    dpi : int
        dots per inch, if exten is '.png'
    """
    if colormap == 'divgmap_blue_red':
        divgmap = cmaps.diverging_cmap(250, 10, l=30)
    elif colormap == 'divgmap_red_blue':
        divgmap = cmaps.diverging_cmap(10, 250, l=30)

    # plot it
    for hlat_name in ccoll.cherns:
        rectps = []
        colorL = []
        print 'all hlats should have same pointer:'
        print 'ccoll[hlat_name][0].haldane_lattice = ', ccoll.cherns[hlat_name][0].haldane_lattice
        print 'ccoll[hlat_name][1].haldane_lattice = ', ccoll.cherns[hlat_name][1].haldane_lattice

        print 'Opening hlat_name = ', hlat_name

        if outdir is None:
            outdir = hcfns.get_cmeshfn(ccoll.cherns[hlat_name][0].haldane_lattice.lp, rootdir=rootdir)

        print 'when saving, will save to ' + outdir + 'filename'

        if maxchern:
            for chernii in ccoll.cherns[hlat_name]:
                # Grab small, medium, and large circles
                ksize = chernii.chern_finsize[:, 2]

                # Build XYloc_sz_nu from all cherns done on this network
                xx = float(chernii.cp['poly_offset'].split('/')[0])
                yy = float(chernii.cp['poly_offset'].split('/')[1])
                nu = chernii.chern_finsize[:, -1]
                ind = np.argmax(np.abs(nu))
                rad = step
                rect = plt.Rectangle((xx-rad*0.5, yy-rad*0.5), rad, rad, ec="none")
                colorL.append(nu[ind])
                rectps.append(rect)
        elif singleksz > 0:
            for chernii in ccoll.cherns[hlat_name]:
                # Grab small, medium, and large circles
                ksize = chernii.chern_finsize[:, 2]

                # Build XYloc_sz_nu from all cherns done on this network
                xx = float(chernii.cp['poly_offset'].split('/')[0])
                yy = float(chernii.cp['poly_offset'].split('/')[1])
                nu = chernii.chern_finsize[:, -1]
                ind = np.argmin(np.abs(ksize - singleksz))
                # print 'ksize = ', ksize
                # print 'singleksz = ', singleksz
                # print 'ind = ', ind
                rad = step
                rect = plt.Rectangle((xx-rad*0.5, yy-rad*0.5), rad, rad, ec="none")
                colorL.append(nu[ind])
                rectps.append(rect)
        elif singleksz_frac > 0:
            for chernii in ccoll.cherns[hlat_name]:
                # Grab small, medium, and large circles
                ksize_frac = chernii.chern_finsize[:, 1]

                # Build XYloc_sz_nu from all cherns done on this network
                xx = float(chernii.cp['poly_offset'].split('/')[0])
                yy = float(chernii.cp['poly_offset'].split('/')[1])
                nu = chernii.chern_finsize[:, -1]
                ind = np.argmin(np.abs(ksize_frac - singleksz_frac))
                # print 'ksize = ', ksize
                # print 'singleksz = ', singleksz
                # print 'ind = ', ind
                rad = step
                rect = plt.Rectangle((xx - rad * 0.5, yy - rad * 0.5), rad, rad, ec="none")
                colorL.append(nu[ind])
                rectps.append(rect)
        else:
            print 'stacking rectangles in list to add to plot...'
            for chernii in ccoll.cherns[hlat_name]:
                # Grab small, medium, and large circles
                # Note: I used to multiply by 0.5 here: Why did I multiply by 0.5 here? Not sure...
                # perhaps before I measured ksize by its diameter (or width) but used radius as an imput for drawing
                # a kitaev region.
                ksize = chernii.chern_finsize[:, 2]
                if max_boxsize is not None:
                    ksize = ksize[ksize < max_boxsize]
                else:
                    if max_boxfrac is not None:
                        cgll = chernii.haldane_lattice.lattice
                        maxsz = max(np.max(cgll.xy[:, 0]) - np.min(cgll.xy[:, 0]),
                                    np.max(cgll.xy[:, 1]) - np.min(cgll.xy[:, 1]))
                        max_boxsize = max_boxfrac * maxsz
                        ksize = ksize[ksize < max_boxsize]
                    else:
                        ksize = ksize
                        max_boxsize = np.max(ksize)

                # print 'ksize =  ', ksize
                # print 'max_boxsize =  ', max_boxsize

                # Build XYloc_sz_nu from all cherns done on this network
                xx = float(chernii.cp['poly_offset'].split('/')[0])
                yy = float(chernii.cp['poly_offset'].split('/')[1])
                nu = chernii.chern_finsize[:, -1]
                rectsizes = ksize / np.max(ksize) * step
                # Choose which rectangles to draw
                if len(ksize) > 30:
                    # Too many rectangles to add to the plot! Limit the number to keep file size down
                    inds2use = np.arange(0, len(ksize), int(float(len(ksize))*0.05))[::-1]
                else:
                    inds2use = np.arange(0, len(ksize), 1)[::-1]
                # print 'Adding ' + str(len(inds2use)) + ' rectangles...'

                # Make a list of the rectangles
                for ind in inds2use:
                    rad = rectsizes[ind]
                    rect = plt.Rectangle((xx-rad*0.5, yy-rad*0.5), rad, rad, ec="none")
                    colorL.append(nu[ind])
                    rectps.append(rect)

        print 'Adding patches to figure...'
        p = PatchCollection(rectps, cmap=divgmap, alpha=1.0, edgecolors='none')
        p.set_array(np.array(np.array(colorL)))
        p.set_clim([-1., 1.])

        if ax is None:
            # Make figure
            FSFS = 8
            Wfig = 90
            x0 = round(Wfig * 0.15)
            y0 = round(Wfig * 0.1)
            ws = round(Wfig * 0.4)
            hs = ws
            wsDOS = ws * 0.3
            hsDOS = hs
            wscbar = wsDOS
            hscbar = wscbar * 0.1
            vspace = 8  # vertical space btwn subplots
            hspace = 8  # horizonl space btwn subplots
            tspace = 10  # space above top figure
            Hfig = y0 + hs + vspace + hscbar + tspace
            fig = sps.figure_in_mm(Wfig, Hfig)
            label_params = dict(size=FSFS, fontweight='normal')
            ax = [sps.axes_in_mm(x0, y0, width, height, label=part, label_params=label_params)
                  for x0, y0, width, height, part in (
                      [Wfig * 0.5 - ws * 0.5, y0, ws, hs, ''],  # Chern vary hlatparam vs ksize
                      [Wfig * 0.5 - wscbar, y0 + hs + vspace, wscbar * 2, hscbar, '']  # cbar for chern
                  )]

            # Add the patches of nu calculations for each site probed
            ax[0].add_collection(p)
            hlat = ccoll.cherns[hlat_name][0].haldane_lattice
            netvis.movie_plot_2D(hlat.lattice.xy, hlat.lattice.BL, 0*hlat.lattice.BL[:, 0],
                             None, None, ax=ax[0], fig=fig, axcb=None,
                             xlimv='auto', ylimv='auto', climv=0.1, colorz=colorz, ptcolor=None, figsize='auto',
                             colormap='BlueBlackRed', bgcolor='#ffffff', axis_off=True, axis_equal=True,
                             lw=0.2)

            # Add title
            ax[0].annotate(title, xy=(0.5, .95), xycoords='figure fraction',
                           horizontalalignment='center', verticalalignment='center')
            if xlabel is not None:
                ax[0].set_xlabel(xlabel)
            if ylabel is not None:
                ax[0].set_xlabel(ylabel)

            # Position colorbar
            sm = plt.cm.ScalarMappable(cmap=divgmap, norm=plt.Normalize(vmin=-1, vmax=1))
            # fake up the array of the scalar mappable.
            sm._A = []
            cbar = plt.colorbar(sm, cax=ax[1], orientation='horizontal', ticks=[-1, 0, 1])
            ax[1].set_xlabel(r'$\nu$')
            ax[1].xaxis.set_label_position("top")
        else:
            # Add the patches of nu calculations for each site probed
            ax.add_collection(p)
            hlat = ccoll.cherns[hlat_name][0].haldane_lattice
            netvis.movie_plot_2D(hlat.lattice.xy, hlat.lattice.BL, 0*hlat.lattice.BL[:, 0],
                                 None, None, ax=ax, fig=plt.gcf(), axcb=None,
                                 xlimv='auto', ylimv='auto', climv=0.1, colorz=colorz, ptcolor=None, figsize='auto',
                                 colormap='BlueBlackRed', bgcolor='#ffffff', axis_off=True, axis_equal=True,
                                 lw=0.2)

            # Add title
            if title is not None and title != 'none':
                ax.annotate(title, xy=(0.5, .95), xycoords='figure fraction',
                            horizontalalignment='center', verticalalignment='center')
            if xlabel is not None:
                ax.set_xlabel(xlabel)
            if ylabel is not None:
                ax.set_xlabel(ylabel)

            if make_cbar:
                # Position colorbar
                sm = plt.cm.ScalarMappable(cmap=divgmap, norm=plt.Normalize(vmin=-1, vmax=1))
                # fake up the array of the scalar mappable.
                sm._A = []
                if cbar_ax is not None:
                    # figure out if cbar_ax is horizontal or vertical
                    if leplt.cbar_ax_is_vertical(cbar_ax):
                        cbar = plt.colorbar(sm, cax=cbar_ax, orientation='vertical', ticks=[-1, 0, 1],
                                            label='Chern\n' + r'number, $\nu$')
                    else:
                        cbar = plt.colorbar(sm, cax=cbar_ax, orientation='horizontal', ticks=[-1, 0, 1],
                                            label=r'Chern number, $\nu$')
                        cbar_ax.set_xlabel(r'Chern number, $\nu$')
                        cbar_ax.xaxis.set_label_position("top")
                else:
                    cbar = plt.colorbar(sm, cax=cbar_ax, orientation='horizontal', ticks=[-1, 0, 1],
                                        label=r'Chern number, $\nu$')

        if save:
            # Save the plot
            # make outdir the hlat_cmesh
            print 'kcollpfns: saving figure:\n outdir =', outdir, ' filename = ', filename
            # outdir = kfns.get_cmeshfn(ccoll.cherns[hlat_name][0].haldane_lattice.lp, rootdir=rootdir)
            if filename == 'chern_varyloc':
                filename += '_Nks'+'{0:03d}'.format(len(ksize)) + '_step' + sf.float2pstr(step) + '_maxbsz' +\
                            sf.float2pstr(max_boxsize) + exten
            print 'saving figure: ' + outdir + filename
            if exten == '.png':
                plt.savefig(outdir + filename, dpi=dpi)
            else:
                plt.savefig(outdir + filename)
            plt.clf()

    return ax, cbar