Python matplotlib.pyplot.GridSpec() Examples

The following are code examples for showing how to use matplotlib.pyplot.GridSpec(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: skultrafast   Author: Tillsten   File: plot_helpers.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stack_ax(num_rows=2, num_cols=1, height_rations=[2, 1]):
    gs = plt.GridSpec(num_rows,
                      num_cols,
                      wspace=0,
                      hspace=0,
                      height_ratios=height_rations)
    #disable ticklabels
    axes = []
    for r in range(num_rows):
        row = []
        for c in range(num_cols):
            ax = plt.subplot(gs[r, c])
            row.append(ax)
            if r != num_rows:
                ax.xaxis.tick_params(label_bottom=False)
            if c != 0:
                ax.yaxis.tick_params(label_left=False)

        axes.append(row) 
Example 2
Project: seqc   Author: ambrosejcarr   File: plot.py    GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, n: int, max_cols=3, scale=3):
        """
        :param n: number of axes to generate
        :param max_cols: maximum number of axes in a given row
        """

        self.n = n
        self.nrows = int(np.ceil(n / max_cols))
        self.ncols = int(min((max_cols, n)))
        figsize = self.ncols * scale, self.nrows * scale

        # create figure
        self.gs = plt.GridSpec(nrows=self.nrows, ncols=self.ncols)
        self.figure = plt.figure(figsize=figsize)

        # create axes
        self.axes = {}
        for i in range(n):
            row = int(i // self.ncols)
            col = int(i % self.ncols)
            self.axes[i] = plt.subplot(self.gs[row, col]) 
Example 3
Project: DETAD   Author: HumamAlwassel   File: false_postive_analysis.py    MIT License 5 votes vote down vote up
def plot_fp_analysis(fp_error_analysis, save_filename, 
                     colors=['#33a02c','#b2df8a','#1f78b4','#fb9a99','#e31a1c','#a6cee3'],
                     error_names=['True Postive', 'Double Detection Err','Wrong Lable Err', 'Localization Err', 'Confusion Err', 'Background Err'],
                     figsize=(10,5), fontsize=24):

    values,labels = [],[]
    _, _, fp_error_types_precentage_df = split_predictions_by_score_ranges(fp_error_analysis,fp_error_analysis.limit_factor)
    order = np.array([4,2,5,3,1,0])
    for this_limit_factor, this_fp_error_types_precentage_df  in fp_error_types_precentage_df.iteritems():
        values+=[this_fp_error_types_precentage_df['avg'].values[order]]
        labels+=['$%dG$' % (this_limit_factor+1)]

    fig = plt.figure(figsize=figsize)
    grid = plt.GridSpec(1, 5)

    lgd = subplot_fp_profile(fig=fig, ax=fig.add_subplot(grid[:-2]),
                             values=values, labels=labels, colors=colors,
                             xticks=error_names,
                             xlabel='Top Predicitons', ylabel='Error Breakdown ($\%$)',
                             title='False Postive Profile', fontsize=fontsize, 
                             ncol=3, legend_loc=(-0.15,1.15))

    order = np.array([4,0,1,3,2])
    subplot_error_type_impact(fig=fig, ax=fig.add_subplot(grid[-2:]),
                              values=np.array([fp_error_analysis.average_mAP_gain.values()]).T[order,:], 
                              labels=np.array(fp_error_analysis.average_mAP_gain.keys())[order], 
                              colors=colors[::-1],
                              xlabel='Error Type', ylabel='Average-mAP$_N$\nImprovment $(\%)$',
                              title='Removing Error Impact', fontsize=fontsize,
                              top=np.ceil(np.max(fp_error_analysis.average_mAP_gain.values())*100*1.1))
    
    plt.tight_layout()
    fig.savefig(save_filename,box_extra_artists=(lgd,), bbox_inches='tight')
    print('[Done] Output analysis is saved in %s' % save_filename) 
Example 4
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 5 votes vote down vote up
def DEBUG_print_ksn_filters(self):
        """
            This function is used to print one ksn profile per river to check the effect of the different filters on the dataset
            BG - 12/01/2018
        """
        plt.clf()
        print("I will now print ksn(chi) with the different filter")
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        for SK in self.df_river["source_key"].unique():
            print("printing river: " +str(SK))

            # Selecting the river
            df = self.df_river[self.df_river["source_key"] == SK]

            fig = plt.figure(1, facecolor='white',figsize=(9,5))

            gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95)
            ax1 = fig.add_subplot(gs[0:100,0:100])

            ax1.scatter(df["chi"], df["m_chi"], c = "r", s = 1, marker = "o", label = "ksn")
            ax1.scatter(df["chi"], df["lumped_ksn"], c = "g", s = 1, marker = "s", label = "lumped ksn")
            ax1.scatter(df["chi"], df["TVD_ksn"], c = "k", s = 1, marker = "+", label = "TVD ksn")

            ax1.legend()

            ax1.set_xlabel(r'$ \chi$')
            ax1.set_ylabel(r'$ k_{sn}$')

            plt.savefig(svdir + self.fprefix + "_ksn_SK_" +str(SK)+".png", dpi = 300)
            plt.clf() 
Example 5
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 5 votes vote down vote up
def DEBUG_print_ksn_outliers(self):
        """
            This function is used to print one ksn profile per river to check the effect of the different filters on the dataset
            BG - 12/01/2018
        """
        plt.clf()
        print("I will now print ksn(chi) with outliers")
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        for SK in self.df_river["source_key"].unique():
            print("printing river: " +str(SK))

            # Selecting the river
            df = self.df_river[self.df_river["source_key"] == SK]
            dfo = self.df_kp[self.df_kp["source_key"] == SK]

            fig = plt.figure(1, facecolor='white',figsize=(9,5))

            gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95)
            ax1 = fig.add_subplot(gs[0:100,0:100])

            ax1.scatter(df["chi"], df["m_chi"], c = "r", s = 1, marker = "o", label = "ksn", alpha = 0.15)
            # ax1.scatter(df["chi"], df["lumped_ksn"], c = "g", s = 1, marker = "s", label = "lumped ksn")
            # ax1.scatter(df["chi"], df["TVD_ksn_NC"], c = "purple", s = 2, marker = "x", label = "TVD ksn non corrected")
            ax1.scatter(df["chi"], df["TVD_ksn"], c = "k", s = 1, marker = "+", label = "TVD ksn")

            ax1.scatter(dfo["chi"][dfo["out"]==1], dfo["delta_ksn"][dfo["out"]==1], c = "purple" , marker = "s", s = 4)
            lim = ax1.get_ylim()
            ax1.vlines(dfo["chi"][dfo["out"]==1],-1000,1000, lw = 0.5, alpha = 0.5)
            ax1.set_ylim(lim)


            ax1.legend()

            ax1.set_xlabel(r'$ \chi$')
            ax1.set_ylabel(r'$ k_{sn}$')

            plt.savefig(svdir + self.fprefix + "_outksn_SK_" +str(SK)+".png", dpi = 300)
            plt.clf() 
Example 6
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 5 votes vote down vote up
def DEBUG_print_KDE(self):
        """
            This function is used to print one ksn profile per river to check the effect of the different filters on the dataset
            BG - 12/01/2018
        """
        plt.clf()
        print("I will now print ksn(chi) with the different KDE")
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        for SK in self.df_kp_raw["source_key"].unique():
            print("printing river: " +str(SK))

            # Selecting the river
            df = self.df_kp_raw[self.df_kp_raw["source_key"] == SK]

            fig = plt.figure(1, facecolor='white',figsize=(9,5))

            gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95)
            ax1 = fig.add_subplot(gs[0:100,0:100])

            ax1.scatter(df["dksn/dchi"], df["KDE"], c = "k", s = 1, marker = "+", label = "ksn")

            ax1.set_xlabel(r'$ \frac{dk_{sn}}{\chi}$')
            ax1.set_ylabel(r'$ KDE_pdf $')

            plt.savefig(svdir + self.fprefix + "_KDE_SK_" +str(SK)+".png", dpi = 300)
            plt.clf() 
Example 7
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 5 votes vote down vote up
def plot_base_to_lip_from_knickpoint_profile(self, df = 0, comparison_point = [], size_format='ESURF', FigFormat='png'):

        if(isinstance(df,int)):
            df = self.knickpoint_raw
        raster_directory = self.fpath+'raster_plots/'
        if not os.path.isdir(raster_directory):
            os.makedirs(raster_directory)

        self.get_base_to_lip_from_knickpoint(df)

        for source in df["source_key"].unique():
            print(source)
            # make a figure with required dimensions
            if size_format == "geomorphology":
                fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5))            
            elif size_format == "big":
                fig = plt.figure(1, facecolor='white',figsize=(16,9))            
            else:
                fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5))

            # create the axis and its position
            ## axis 1: The Chi profile and the knickpoints
            gs = plt.GridSpec(100,100,bottom=0.15,left=0.15,right=0.95,top=0.95)
            ax = fig.add_subplot(gs[0:100,0:100])
            CN = self.chanNet[self.chanNet["source_key"] == source]
            ax.plot(CN["chi"], CN["elevation"],zorder = 100)
            for i in self.base_to_lip_from_knickpoint:
                if i.iloc[0]["source_key"] == source:
                    ax.scatter(i.iloc[0]["chi"],i.iloc[0]["segmented_elevation"], s = 10, c = "r", zorder = 150)
                    ax.scatter(i.iloc[-1]["chi"],i.iloc[-1]["segmented_elevation"], s = 10, c = "b", zorder = 150)

            if(len(comparison_point) == 2):
                print("I am adding the comparison_point to the profiles")
                ax.scatter(comparison_point[0]["chi"][comparison_point[0]["source_key"] == source], comparison_point[0]["elevation"][comparison_point[0]["source_key"] == source], marker = "x", c = "r", s = 20,lw = 0.8, zorder = 500)
                ax.scatter(comparison_point[1]["chi"][comparison_point[1]["source_key"] == source], comparison_point[1]["elevation"][comparison_point[1]["source_key"] == source], marker = "x", c = "y", s = 20,lw = 0.8, zorder = 500)


            plt.savefig(raster_directory +"profile_base_to_lip"+str(source)+".png",dpi = 300)
            plt.clf() 
Example 8
Project: viznet   Author: GiggleLiu   File: test_brush.py    MIT License 5 votes vote down vote up
def __enter__(self):
        plt.ion()
        plt.figure(figsize=self.figsize)
        self.gs = plt.GridSpec(*self.grid)
        return self 
Example 9
Project: sklearn_pydata2015   Author: jakevdp   File: figures.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_image_components(x, coefficients=None, mean=0, components=None,
                          imshape=(8, 8), n_components=6, fontsize=12):
    if coefficients is None:
        coefficients = x
        
    if components is None:
        components = np.eye(len(coefficients), len(x))
        
    mean = np.zeros_like(x) + mean
        

    fig = plt.figure(figsize=(1.2 * (5 + n_components), 1.2 * 2))
    g = plt.GridSpec(2, 5 + n_components, hspace=0.3)

    def show(i, j, x, title=None):
        ax = fig.add_subplot(g[i, j], xticks=[], yticks=[])
        ax.imshow(x.reshape(imshape), interpolation='nearest')
        if title:
            ax.set_title(title, fontsize=fontsize)

    show(slice(2), slice(2), x, "True")

    approx = mean.copy()
    show(0, 2, np.zeros_like(x) + mean, r'$\mu$')
    show(1, 2, approx, r'$1 \cdot \mu$')

    for i in range(0, n_components):
        approx = approx + coefficients[i] * components[i]
        show(0, i + 3, components[i], r'$c_{0}$'.format(i + 1))
        show(1, i + 3, approx,
             r"${0:.2f} \cdot c_{1}$".format(coefficients[i], i + 1))
        plt.gca().text(0, 1.05, '$+$', ha='right', va='bottom',
                       transform=plt.gca().transAxes, fontsize=fontsize)

    show(slice(2), slice(-2, None), approx, "Approx") 
Example 10
Project: MMPP   Author: kkingstoun   File: prepareplot.py    MIT License 5 votes vote down vote up
def __init__(self, lpx, lpy):
		self.fig, self.axes = plt.subplots(lpx*lpy)
		self.colorbars = []
		self.ai =0
		self.grid = plt.GridSpec(lpx, lpy, wspace=0.4, hspace=0.3)
		self.grid.update(hspace=0.5)
		style.use("seaborn-white") 
Example 11
Project: scvelo   Author: theislab   File: scatter.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gridspec(nrows=1, ncols=2, figsize=None, dpi=None):
    if figsize is None: figsize = rcParams['figure.figsize']
    gs = pl.GridSpec(nrows, ncols, pl.figure(None, (figsize[0] * ncols, figsize[1] * nrows), dpi=dpi))
    return gs 
Example 12
Project: scvelo   Author: theislab   File: simulation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def simulation(adata, var_names='all', legend_loc='upper right', legend_fontsize=20, linewidth=None, dpi=None,
               xkey='true_t', ykey=['unspliced', 'spliced', 'alpha'], colors=['darkblue', 'darkgreen', 'grey'], **kwargs):
    from ..tools.utils import make_dense
    from .scatter import scatter
    var_names = adata.var_names if var_names is 'all' else [name for name in var_names if name in adata.var_names]

    figsize = rcParams['figure.figsize']
    ncols = len(var_names)
    for i, gs in enumerate(pl.GridSpec(1, ncols, pl.figure(None, (figsize[0] * ncols, figsize[1]), dpi=dpi))):
        idx = np.where(adata.var_names == var_names[i])[0][0]

        alpha, ut, st = compute_dynamics(adata, idx)

        t = adata.obs[xkey] if xkey in adata.obs.keys() else make_dense(adata.layers['fit_t'][:, idx])
        idx_sorted = np.argsort(t)
        t = t[idx_sorted]

        ax = pl.subplot(gs)
        _kwargs = {'alpha': .3, 'title': '', 'xlabel': 'time', 'ylabel': 'counts'}
        _kwargs.update(kwargs)
        linewidth = 1 if linewidth is None else linewidth

        ykey = [ykey] if isinstance(ykey, str) else ykey
        for j, key in enumerate(ykey):
            if key in adata.layers:
                y = make_dense(adata.layers[key][:, idx])[idx_sorted]
                ax = scatter(x=t, y=y, color=colors[j], ax=ax, show=False, **_kwargs)

            if key is 'unspliced':
                ax.plot(t, ut, label='unspliced', color=colors[j], linewidth=linewidth)
            elif key is 'spliced':
                ax.plot(t, st, label='spliced', color=colors[j], linewidth=linewidth)
            elif key is 'alpha':
                ax.plot(t, alpha, label='alpha', linestyle='--', color=colors[j], linewidth=linewidth)

        pl.xlim(0)
        pl.ylim(0)
        if legend_loc is not 'none' and i == ncols-1:
            pl.legend(loc=legend_loc, fontsize=legend_fontsize) 
Example 13
Project: velocyto.py   Author: velocyto-team   File: analysis.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot_phase_portraits(self, genes: List[str]) -> None:
        """Plot spliced-unspliced scatterplots resembling phase portraits

        Arguments
        ---------
        genes: List[str]
            A list of gene symbols.
        """
        n = len(genes)
        sqrtn = int(np.ceil(np.sqrt(n)))
        gs = plt.GridSpec(sqrtn, int(np.ceil(n / sqrtn)))
        for i, gn in enumerate(genes):
            self._plot_phase_portrait(gn, gs[i]) 
Example 14
Project: odin-ai   Author: imito   File: figures.py    MIT License 5 votes vote down vote up
def plot_gridSpec(nrow, ncol, wspace=None, hspace=None):
  """
  Example
  -------
  grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)
  plt.subplot(grid[0, 0])
  plt.subplot(grid[0, 1:])
  plt.subplot(grid[1, :2])
  plt.subplot(grid[1, 2])
  """
  from matplotlib import pyplot as plt
  grid = plt.GridSpec(nrows=nrow, ncols=ncol, wspace=wspace, hspace=hspace)
  yield grid 
Example 15
Project: MachineLearning   Author: LocalGroupAstrostatistics2015   File: figures.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_image_components(x, coefficients=None, mean=0, components=None,
                          imshape=(8, 8), n_components=6, fontsize=12):
    if coefficients is None:
        coefficients = x
        
    if components is None:
        components = np.eye(len(coefficients), len(x))
        
    mean = np.zeros_like(x) + mean
        

    fig = plt.figure(figsize=(1.2 * (5 + n_components), 1.2 * 2))
    g = plt.GridSpec(2, 5 + n_components, hspace=0.3)

    def show(i, j, x, title=None):
        ax = fig.add_subplot(g[i, j], xticks=[], yticks=[])
        ax.imshow(x.reshape(imshape), interpolation='nearest')
        if title:
            ax.set_title(title, fontsize=fontsize)

    show(slice(2), slice(2), x, "True")

    approx = mean.copy()
    show(0, 2, np.zeros_like(x) + mean, r'$\mu$')
    show(1, 2, approx, r'$1 \cdot \mu$')

    for i in range(0, n_components):
        approx = approx + coefficients[i] * components[i]
        show(0, i + 3, components[i], r'$c_{0}$'.format(i + 1))
        show(1, i + 3, approx,
             r"${0:.2f} \cdot c_{1}$".format(coefficients[i], i + 1))
        plt.gca().text(0, 1.05, '$+$', ha='right', va='bottom',
                       transform=plt.gca().transAxes, fontsize=fontsize)

    show(slice(2), slice(-2, None), approx, "Approx") 
Example 16
Project: pymps   Author: GiggleLiu   File: plotlib.py    MIT License 5 votes vote down vote up
def __enter__(self):
        _setup_mpl()
        plt.ion()
        self.fig = plt.figure(figsize=self.figsize)
        if self.graph_layout is None:
            self.ax = plt.subplot(111)
        else:
            self.ax = []
            self.gs = plt.GridSpec(*self.graph_layout)
            for i in range(self.graph_layout[0]):
                for j in range(self.graph_layout[1]):
                    self.ax.append(plt.subplot(self.gs[i, j]))
        return self 
Example 17
Project: pyplis   Author: jgliss   File: plumespeed.py    GNU General Public License v3.0 4 votes vote down vote up
def plot(self, date_fmt=None, fig=None, **kwargs):
        """Plot showing detailed information about this time series.

        Parameters
        ----------
        date_fmt : str
            date string formatting for x-axis
        fig : figure
            matplotlib figure containing 3 subplots

        """
        try:
            ax = fig.axes
            ax2 = ax[0]
            ax0 = ax[1]
            ax1 = ax[2]
        except BaseException:
            fig = figure()
            gs = GridSpec(3, 1, height_ratios=[.4, .4, .2], hspace=0.05)
            # for significance plot (gets x label)
            ax2 = fig.add_subplot(gs[2])
            ax0 = fig.add_subplot(gs[0], sharex=ax2)  # for orientation plot
            ax1 = fig.add_subplot(gs[1], sharex=ax2)  # for displ. lens

        ax1.yaxis.tick_right()
        ax1.yaxis.set_label_position("right")

        sign = Series(self.significance, self.start_acq)
        sign.index = sign.index.to_pydatetime()
        sign.plot(ax=ax2, **kwargs)
        ax2.set_ylabel("Significance")
        ax2.set_ylim([0, 1])
        ax2.set_yticks([0, .2, .4, .6, .8, 1])
        ax2.grid()
        try:
            if date_fmt is not None:
                ax2.xaxis.set_major_formatter(DateFormatter(date_fmt))
        except BaseException:
            pass

        self.plot_directions(ax=ax0, date_fmt=date_fmt, **kwargs)
        self.plot_magnitudes(ax=ax1, date_fmt=date_fmt, **kwargs)
        ax0.set_xticklabels([])
        ax1.set_xticklabels([])
        try:
            gs.update(hspace=0.05, top=0.97, bottom=0.07)
        except BaseException:
            pass
        return fig 
Example 18
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_ChiPlotting.py    MIT License 4 votes vote down vote up
def ChannelProfilePlot(DataDirectory, fname_prefix, FigFormat='png', size_format='ESURF',basin_key=[0], source_key=[0]):
    """
    This function makes a simple river long profile plot from the chi data map.

    Args:
        DataDirectory (str): the data directory
        fname_prefix (str): the name of the DEM without extension
        FigFormat(str): format of the figure, e.g. png, svg
        size_format (str): size of the figure, can be either 'geomorphology', 'big', or 'ESURF'
        basin_key (list): basin keys to analyse
        source_key (list): source keys of the channels you want to plot.

    Returns:
        long profile plot

    Author: FJC
    """
    df = Helper.ReadChiDataMapCSV(DataDirectory,fname_prefix)

    # mask for the basin and the channel
    df = df[df['basin_key'].isin(basin_key)]
    df = df[df['source_key'].isin(source_key)]

    # set up the figure
    # Set up fonts for plots
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size

    # make a figure
    if size_format == "geomorphology":
        fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5))
        #l_pad = -40
    elif size_format == "big":
        fig = plt.figure(1, facecolor='white',figsize=(16,9))
        #l_pad = -50
    else:
        fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.2))
        #l_pad = -35

    gs = plt.GridSpec(100,100,bottom=0.2,left=0.05,right=0.95,top=0.95)
    ax = fig.add_subplot(gs[5:100,10:95])

    elevation = df['elevation'].tolist()
    flow_distance = df['flow_distance'].tolist()

    ax.plot(flow_distance, elevation, c='b')
    ax.set_xlabel('Distance upstream from outlet (m)')
    ax.set_ylabel('Elevation (m)')

    newFilename = DataDirectory+fname_prefix+"_profiles."+FigFormat
    plt.savefig(newFilename,format=FigFormat,dpi=300)
    ax.cla()
    plt.close(fig) 
Example 19
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def DEBUG_print_ksn_dksndchi(self):
        """
            This function is used to print one ksn profile per river to check the effect of the different filters on the dataset
            BG - 12/01/2018
        """
        plt.clf()
        print("I will now print ksn(chi) with outliers")
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        for SK in self.df_river["source_key"].unique():
            print("printing river: " +str(SK))

            # Selecting the river
            df = self.df_river[self.df_river["source_key"] == SK]
            dfo = self.df_kp_raw[self.df_kp_raw["source_key"] == SK]

            fig = plt.figure(1, facecolor='white',figsize=(9,5))

            gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.90,top=0.95)
            ax1 = fig.add_subplot(gs[0:100,0:100])
            ax2 = fig.add_subplot(gs[0:100,0:100], facecolor = "None")



            ax1.scatter(df["chi"], df["m_chi"], c = "gray", s = 1, marker = "o", label = "ksn")
            # ax1.scatter(df["chi"], df["lumped_ksn"], c = "g", s = 1, marker = "s", label = "lumped ksn")
            
            ax1.scatter(df["chi"], df["TVD_ksn"], c = "k", s = 1, marker = "+", label = "TVD ksn")
            ylim = ax1.get_ylim()
            ax2.scatter(dfo["chi"], dfo["delta_ksn"], c = "r", s = 3, marker = "s", label = r'$ \frac{d(TVD_ksn)}{d\chi}$')

            ax2.yaxis.set_label_position('right')
            ax2.yaxis.set_ticks_position('right')
            ax2.xaxis.set_visible(False)
            ax1.yaxis.set_label_position('left')
            ax1.yaxis.set_ticks_position('left')



            ax2.set_xlim(ax1.get_xlim())
            ax1.set_ylim(ylim)
            # ax1.scatter(dfo["chi"][dfo["out_MZS"]==1], dfo["delta_ksn"][dfo["out_MZS"]==1], c = "r" , marker = "s", s = 2)


            # ax1.legend()

            ax1.set_xlabel(r'$ \chi$')
            ax1.set_ylabel(r'$ k_{sn}$')
            ax2.set_ylabel(r'$ \frac{d(TVD_ksn)}{d\chi}$')

            plt.savefig(svdir + self.fprefix + "_ksn_rawkp_SK_" +str(SK)+".png", dpi = 300)
            # plt.show()
            plt.clf() 
Example 20
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def plot_mchi_segments(self, method = "deriv_ksn", group = "source_key"):
        """
            Statistical plot to calibrate the KDE per rivers
        """
        print("I am going to plot the m_chi/ksn segments to check my knickpoints")
                # check if a directory exists for the chi plots. If not then make it.
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        if method == "deriv_ksn":
            out_method = "out_KDE_ksn"

        elif method == "deriv_delta_ksn":
            out_method = "out_KDE_dksn"

        
        for source in self.df[group].unique():
            if not np.isnan(source):
                this_df = self.df[self.df[group] == source]
                this_MCdf = self.CNMC[self.CNMC[group] == source]
                fig = plt.figure(2, facecolor='white',figsize=(9,5))
                gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95)
                ax1 = fig.add_subplot(gs[0:100,0:100])
                ax2 = fig.add_subplot(gs[0:100,0:100], facecolor = "None")

                ax2.scatter(this_MCdf["chi"], this_MCdf["m_chi"], s = 1, lw = 1, c = this_MCdf["m_chi"], cmap = "RdBu_r")
                ou = this_df[this_df[out_method]==1]
                ax1.scatter(ou["chi"], ou["ksn"], s = 40, c = ou["source_key"], lw = 1,marker = "+", label = "outliers before merging", cmap = "jet")
                ax1.vlines(ou["chi"], ou["ksn"].min() , ou["ksn"].max(), linestyles  = "dashdot", lw = 0.5 )
                ouf = self.final_out[self.final_out[group] == source]
                ax1.scatter(ouf["chi"], ouf["ksn"], marker = "x", s = 50, lw = 1,c = "g", label = "outliers after merging" )


                ax2.set_xlabel(r'$\chi$')
                ax2.set_ylabel(r"$M_\chi$")
                #ax2.set_xlim(0,1000)
                #ax2.scatter(this_df["deriv_delta_ksn"], this_df["KDE_delta_ksn"], s = 100, marker = "x", lw = 1, c = "k",label = "KDE d2(ksn)/d(chi)")
                ax1.xaxis.set_visible(False)
                ax1.yaxis.set_ticks_position("right")
                ax1.yaxis.set_label_position("right")
                ax1.set_ylabel(r'$\Delta K_{sn}$')
                ax1.set_xlim(ax2.get_xlim())
                ax1.legend()

                plt.title(group + " #" +str(source))

                plt.savefig(svdir+"M_chi_plot_"+ str(group)+ "_" + str(source) + "_out_" + method+ ".png", dpi = 300)
                plt.clf() 
Example 21
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def plot_chi_profiles(self, method = "deriv_ksn", group = "source_key"):
        """
            Statistical plot to calibrate the KDE per rivers
        """
        print("I am going to print the chi profile per river/basins depending on what you asked")
                # check if a directory exists for the chi plots. If not then make it.
        svdir = self.fpath+'river_plots/'
        if not os.path.isdir(svdir):
            os.makedirs(svdir)

        if method == "deriv_ksn":
            out_method = "out_KDE_ksn"

        elif method == "deriv_delta_ksn":
            out_method = "out_KDE_dksn"

        
        for source in self.df[group].unique():
            if not np.isnan(source):
                this_df = self.df[self.df[group] == source]
                this_MCdf = self.CNMC[self.CNMC[group] == source]
                fig = plt.figure(2, facecolor='white',figsize=(9,5))
                gs = plt.GridSpec(100,100,bottom=0.10,left=0.10,right=0.95,top=0.95)
                ax1 = fig.add_subplot(gs[0:100,0:90])
                ax2 = fig.add_subplot(gs[0:100,0:90], facecolor = "None")
                axa = fig.add_subplot(gs[0:100,90:100])
                cax = fig.add_subplot(gs[0:100,91:95])


                ax2.scatter(this_MCdf["chi"], this_MCdf["elevation"], s = 1, lw = 0, c = this_MCdf["source_key"], cmap = "RdBu_r")
                ou = self.final_out[self.final_out[group] == source]
                cb = ax1.scatter(ou["chi"], ou["elevation"], s = 50, c = ou["ksn"], lw = 0,marker = "o", label = "Knickpoint", cmap = "RdBu_r")

                ax2.set_xlabel(r'$\chi$')
                ax2.set_ylabel("elevation (m)")
                #ax2.set_xlim(0,1000)
                #ax2.scatter(this_df["deriv_delta_ksn"], this_df["KDE_delta_ksn"], s = 100, marker = "x", lw = 1, c = "k",label = "KDE d2(ksn)/d(chi)")
                ax1.xaxis.set_visible(False)
                ax1.yaxis.set_visible(False)

                ax1.set_xlim(ax2.get_xlim())
                ax1.set_ylim(ax2.get_ylim())
                ax1.set_title(group + " #" +str(source))
                ax1.legend(loc = 2)
                

                plt.colorbar(cb,cax = cax, ax = axa)
                axa.axis("off")

                plt.savefig(svdir+"Chi_profile_"+ str(group)+ "_" + str(source) + "_out_" + method+ ".png", dpi = 300)
                plt.clf() 
Example 22
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def plot_diff_ratio(PointData, DataDirectory, saveName = "Basic_diff_ratio", save_fmt = ".png", size_format = "ESURF", log_data = False):
    """
    Basic plot to have a general view of the knickpoints: diff against ratio colored by elevation

    Args:
        PointData: A PointData object
        DataDirectory: Where the data is saved
        saveName: save name

    returns:
        Nothing, sorry.
    Author: BG
    """
    plt.clf()
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size

    # make a figure
    if size_format == "geomorphology":
        fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5))
        l_pad = -40
    elif size_format == "big":
        fig = plt.figure(1, facecolor='white',figsize=(16,9))
        l_pad = -50
    else:
        fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5))
        l_pad = -35

    gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
    ax = fig.add_subplot(gs[25:100,10:95])

    diff = PointData.QueryData("diff")
    ratio = PointData.QueryData("ratio")

    if(log_data):
        print("I am logging the data")
        diff = np.log10(diff)
        ratio = np.log10(ratio)

    elevation =PointData.QueryData("elevation")
    ax.scatter(diff,ratio, s=0.5, lw = 0, c = elevation)
    ax.set_xlabel("Diff")
    ax.set_ylabel("Ratio")

    plt.savefig(DataDirectory+saveName+save_fmt,dpi=500) 
Example 23
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def plot_basic_DA(PointData, DataDirectory, saveName = "Basic_DA", save_fmt = ".png", size_format = "ESURF", log_data = False):
    """
    Basic plot to have a general view of the knickpoints: drainage area against ratio and diff colored by elevation

    Args:
        PointData: A PointData object
        DataDirectory: Where the data is saved
        saveName: save name

    returns:
        Nothing, sorry.
    Author: BG
    """
    plt.clf()
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size

    # make a figure
    if size_format == "geomorphology":
        fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5))
        l_pad = -40
    elif size_format == "big":
        fig = plt.figure(2, facecolor='white',figsize=(16,9))
        l_pad = -50
    else:
        fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5))
        l_pad = -35

    diff = PointData.QueryData("diff")
    ratio = PointData.QueryData("ratio")
    DA = PointData.QueryData("drainage area")

    gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
    ax1 = fig.add_subplot(gs[10:50,10:95])
    ax2 = fig.add_subplot(gs[50:100,10:95])



    if(log_data):
        print("I am logging the data")
        diff = np.log10(diff)
        ratio = np.log10(ratio)

    elevation = PointData.QueryData("elevation")
    DA = np.log10(DA)
    ax1.scatter(DA,ratio, s=0.7, lw = 0, c = elevation)
    ax1.set_ylabel("Ratio")
    ax1.tick_params(axis = 'x', length = 0, width = 0, labelsize = 0)
    ax1.spines['bottom'].set_visible(False)
    ax2.scatter(DA,diff,s=0.7, lw = 0, c = elevation)
    ax2.set_ylabel("Diff")
    ax2.set_xlabel("Drainage area")
    #ax2.set_xticks([1,2,3,4,5,6,7])
    ax2.tick_params(axis = 'x', labelsize = 6)
    ax1.set_xticks([4,5,6,7,8,9,10])
    ax2.set_xticks([4,5,6,7,8,9,10])
    ax2.set_xticklabels([ur"$10^{4}$",ur"$10^{5}$",ur"$10^{6}$",ur"$10^{7}$",ur"$10^{8}$",ur"$10^{9}$",ur"$10^{10}$"])

    plt.savefig(DataDirectory+saveName+save_fmt,dpi=500) 
Example 24
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def plot_basic_Z(PointData, DataDirectory, saveName = "Basic_Z", save_fmt = ".png", size_format = "ESURF", log_data = False):
    """
    Basic plot to have a general view of the knickpoints: flow distance against ratio and diff colored by elevation

    Args:
        PointData: A PointData object
        DataDirectory: Where the data is saved
        saveName: save name

    returns:
        Nothing, sorry.
    Author: BG
    """
    plt.clf()
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size

    # make a figure
    if size_format == "geomorphology":
        fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5))
        l_pad = -40
    elif size_format == "big":
        fig = plt.figure(2, facecolor='white',figsize=(16,9))
        l_pad = -50
    else:
        fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5))
        l_pad = -35

    diff = PointData.QueryData("diff")
    ratio = PointData.QueryData("ratio")
    Z = PointData.QueryData("elevation")

    gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
    ax1 = fig.add_subplot(gs[10:50,10:95])
    ax2 = fig.add_subplot(gs[50:100,10:95])



    if(log_data):
        print("I am logging the data")
        diff = np.log10(diff)
        ratio = np.log10(ratio)

    sign = PointData.QueryData("sign")

    ax1.scatter(Z,ratio, s=0.7, lw = 0, c = sign)
    ax1.set_ylabel("Ratio")
    ax1.tick_params(axis = 'x', length = 0, width = 0, labelsize = 0)
    ax1.spines['bottom'].set_visible(False)
    ax2.scatter(Z,diff,s=0.7, lw = 0, c = sign)
    ax2.set_ylabel("Diff")
    ax2.set_xlabel("elevation")

    #ax2.tick_params(axis = 'x', labelsize = 6)
    #ax1.set_xticks([4,5,6,7,8,9,10])
    #ax2.set_xticks([4,5,6,7,8,9,10])
    #ax2.set_xticklabels([ur"$10^{4}$",ur"$10^{5}$",ur"$10^{6}$",ur"$10^{7}$",ur"$10^{8}$",ur"$10^{9}$",ur"$10^{10}$"])

    plt.savefig(DataDirectory+saveName+save_fmt,dpi=500) 
Example 25
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def plot_pdf_diff_ratio(df, DataDirectory, saveName = "pdf_diff_ratio", save_fmt = ".png", size_format = "ESURF",  xlim =[]):
    """
    Basic plot to have a general view of the knickpoints: flow distance against ratio and diff colored by elevation

    Args:
        PointData: A PointData object
        DataDirectory: Where the data is saved
        saveName: save name

    returns:
        Nothing, sorry.
    Author: BG
    """
    plt.clf()
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size

    # make a figure
    if size_format == "geomorphology":
        fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5))
        l_pad = -40
    elif size_format == "big":
        fig = plt.figure(2, facecolor='white',figsize=(16,9))
        l_pad = -50
    else:
        fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5))
        l_pad = -35


    gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
    ax1 = fig.add_subplot(gs[10:50,10:95])
    ax2 = fig.add_subplot(gs[50:100,10:95])


    ax1.scatter(df["ratio"],norm.pdf(df["ratio"]),lw =0, s = 1, c = "red")
    ax1.set_ylabel("Ratio")
    ax1.tick_params(axis = 'x', length = 0, width = 0, labelsize = 0)
    ax1.spines['bottom'].set_visible(False)
    ax2.scatter(df["diff"],norm.pdf(df["diff"]),lw =0, s = 1, c = "red")
    ax2.set_ylabel("Diff")
    ax2.set_xlabel("PDF")


    #'###### Setting the limits
    if(xlim != []):
        ax2.set_xlim(xlim[0],xlim[1])
        ax1.set_xlim(xlim[0],xlim[1])



    #ax2.tick_params(axis = 'x', labelsize = 6)
    #ax1.set_xticks([4,5,6,7,8,9,10])
    #ax2.set_xticks([4,5,6,7,8,9,10])
    #ax2.set_xticklabels([ur"$10^{4}$",ur"$10^{5}$",ur"$10^{6}$",ur"$10^{7}$",ur"$10^{8}$",ur"$10^{9}$",ur"$10^{10}$"])

    plt.savefig(DataDirectory+saveName+save_fmt,dpi=500) 
Example 26
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def violin_by_bin(ldf, DataDirectory, saveName = "Violin", column = "elevation", size_format = "ESURF"):

    """
    Will plot violin from a list of bins. NOT READY YET.

    Author: BG

    matplotlib description:
        Violin plots are similar to histograms and box plots in that they show
    an abstract representation of the probability distribution of the
    sample. Rather than showing counts of data points that fall into bins
    or order statistics, violin plots use kernel density estimation (KDE) to
    compute an empirical distribution of the sample. That computation
    is controlled by several parameters. This example demonstrates how to
    modify the number of points at which the KDE is evaluated (``points``)
    and how to modify the band-width of the KDE (``bw_method``).

    For more information on violin plots and KDE, the scikit-learn docs
    have a great section: http://scikit-learn.org/stable/modules/density.html
    """

    plt.clf()
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size

    # make a figure
    if size_format == "geomorphology":
        fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5))
        l_pad = -40
    elif size_format == "big":
        fig = plt.figure(2, facecolor='white',figsize=(16,9))
        l_pad = -50
    else:
        fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5))
        l_pad = -35


    gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
    ax1 = fig.add_subplot(gs[10:50,10:95])
    ax2 = fig.add_subplot(gs[50:100,10:95])


    ax2.set_ylabel("Ratio")
    ax1.set_ylabel("Diff")
    ax2.set_xlabel(column)
    plt.savefig(DataDirectory+saveName+save_fmt,dpi=500) 
Example 27
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def pdf_from_bin(ldf, DataDirectory, saveName = "BasicPDF_", column = "elevation", size_format = "ESURF" ):

    """
    Produce some simple pdf plots from a list of pandas dataframe.

    Arg:

    Returns: nothing, but produce a plot.

    Author: BG
    """

    for inch in ldf:
        plt.clf()
        label_size = 10
        rcParams['font.family'] = 'sans-serif'
        rcParams['font.sans-serif'] = ['Liberation Sans']
        rcParams['font.size'] = label_size

        # make a figure
        if size_format == "geomorphology":
            fig = plt.figure(2, facecolor='white',figsize=(6.25,3.5))
            l_pad = -40
        elif size_format == "big":
            fig = plt.figure(2, facecolor='white',figsize=(16,9))
            l_pad = -50
        else:
            fig = plt.figure(2, facecolor='white',figsize=(4.92126,3.5))
            l_pad = -35



        gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
        ax1 = fig.add_subplot(gs[10:50,10:95])
        ax2 = fig.add_subplot(gs[50:100,10:95])

        ax2.scatter(ldf[inch]["diff"],norm.pdf(ldf[inch]["diff"]), s = 1.5, lw = 0)
        ax1.scatter(ldf[inch]["ratio"],norm.pdf(ldf[inch]["ratio"]), s = 1.5, lw = 0)

        ax2.set_ylabel("PDF (Diff)")
        ax1.set_ylabel("PDF (Ratio)")
        ax2.set_xlabel("Diff/ratio binned by " + column + "_" + inch)
        plt.savefig(DataDirectory+saveName+inch+"_"+column+".png",dpi=500) 
Example 28
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_KnickpointPlotting_old.py    MIT License 4 votes vote down vote up
def pdf_from_bin_one_col(ldf, DataDirectory, saveName = "BasicPDF_", column = "elevation", size_format = "ESURF", pdf_col = "diff", combine_diff_sign = False, argsort = False ):

    """
    Produce some simple pdf plots from a dict of pandas dataframe.

    Arg:

    Returns: nothing, but produce a plot.

    Author: BG
    """




    for inch in ldf:
        plt.clf()
        label_size = 10
        rcParams['font.family'] = 'sans-serif'
        rcParams['font.sans-serif'] = ['Liberation Sans']
        rcParams['font.size'] = label_size



        if(combine_diff_sign):
            ldf[inch]["diff"][ldf[inch]["sign"] == -1] = -ldf[inch]["diff"][ldf[inch]["sign"] == -1]

        data = np.array(ldf[inch][pdf_col].values)


        # make a figure
        if size_format == "geomorphology":
            fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5))
            l_pad = -40
        elif size_format == "big":
            fig = plt.figure(1, facecolor='white',figsize=(16,9))
            l_pad = -50
        else:
            fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.5))
            l_pad = -35



        gs = plt.GridSpec(100,100,bottom=0.15,left=0.1,right=1.0,top=1.0)
        ax1 = fig.add_subplot(gs[10:100,5:95])

        print(data.shape)
        if(data.shape[0]>0):
            ax1.hist(data, 100, normed=1, facecolor='green', alpha=0.75)






        ax1.set_ylabel("PDF")
        ax1.set_xlabel("elevation by " + pdf_col)
        ax1.set_xlim(-100,100)
        plt.savefig(DataDirectory+saveName+inch+"_"+column+".png",dpi=500) 
Example 29
Project: LSDMappingTools   Author: LSDtopotools   File: LSDMap_DrainageCapture.py    MIT License 4 votes vote down vote up
def PlotBasinPerimeter(DataDirectory, fname_prefix, size_format='ESURF', FigFormat='png'):
    """
    Make a plot of the basin perimeter ordered by the outlet

    Args:
        DataDirectory (str): the data directory
        fname_prefix (str): filename of the DEM without extension
        size_format (str): Can be "big" (16 inches wide), "geomorphology" (6.25 inches wide), or "ESURF" (4.92 inches wide) (defualt esurf).
        FigFormat (str): The format of the figure. Usually 'png' or 'pdf'. If "show" then it calls the matplotlib show() command.

    Author: FJC
    """
    # check if a directory exists for the perimeter plots. If not then make it.
    this_dir = DataDirectory+'basin_perimeters/'
    if not os.path.isdir(this_dir):
        os.makedirs(this_dir)

    # Set up fonts for plots
    label_size = 10
    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = ['Liberation Sans']
    rcParams['font.size'] = label_size

    # make a figure
    if size_format == "geomorphology":
        fig = plt.figure(1, facecolor='white',figsize=(6.25,3.5))
        #l_pad = -40
    elif size_format == "big":
        fig = plt.figure(1, facecolor='white',figsize=(16,9))
        #l_pad = -50
    else:
        fig = plt.figure(1, facecolor='white',figsize=(4.92126,3.2))
        #l_pad = -35

    PerimeterDF = Helper.ReadPerimeterCSV(DataDirectory, fname_prefix)

    gs = plt.GridSpec(100,100,bottom=0.15,left=0.05,right=0.95,top=0.95)
    ax = fig.add_subplot(gs[5:100,10:95])

    # plot the data
    ax.plot(PerimeterDF['node_key'],PerimeterDF['elevation'])

    # set the axis labels
    ax.set_xlabel('Perimeter node ordered from outlet')
    ax.set_ylabel('Node elevation')

    newFilename = this_dir+fname_prefix+"_basin_perimeter."+FigFormat
    plt.savefig(newFilename,format=FigFormat,dpi=300)
    ax.cla()
    plt.close(fig) 
Example 30
Project: VisualizeThemAll   Author: zc8424   File: plot.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def show_plots(title, date_tickers, o, h, l, c, v, operations, x1, x2, extra=[]):
    n = len(date_tickers)
    # x1,x2为横轴显示范围, x1d,x2d为横轴数据索引范围(0~n-1)
    x1d=x1
    x2d=x2
    if x1d<0:
        x1d=0
    if x2d >= n:
        x2d = n - 1

    ymin = numpy.array(l[x1d:x2d+1]).min()
    ymax = numpy.array(h[x1d:x2d+1]).max()
    height = ymax - ymin
    y1main = ymin - height * 0.12
    y2main = ymax + height * 0.12
    arrow_len = height * 0.04 # arrow_len = head_length

    fig = plt.figure()
    grid = plt.GridSpec(3, 1, hspace=0.15)
    main_ax = plt.subplot(grid[0:2,0])
    extra_ax = plt.subplot(grid[2,0], sharex=main_ax)
    fig.subplots_adjust(bottom=0.2)

    plot_main(main_ax, n, o, h, l, c, operations, arrow_len)

    def format_date(x,pos=None):
        if x<0 or x>len(date_tickers)-1:
            return ''
        return date_tickers[int(x-0.5)][2:]
    main_ax.xaxis.set_visible(False)
    main_ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    main_ax.axis((x1-0.5,x2+0.5,y1main,y2main))
    main_ax.set_facecolor("black")
    main_ax.set_title(title)

    # 如extra有数据, 则绘制在副图上, 否则把成交量绘制在副图上
    if len(extra) > 0:
        extra_ax.plot(range(n), extra)
        y1extra = numpy.array(extra[x1d:x2d+1]).min()
        y2extra = numpy.array(extra[x1d:x2d+1]).max()
    else:
        plot_volume(extra_ax, n, v)
        y1extra = 0.0
        y2extra = numpy.array(v[x1d:x2d+1]).max() * 1.08
        extra_ax.set_ylabel("Volume")
    extra_ax.axis(ymin=y1extra,ymax=y2extra)
    extra_ax.set_facecolor("black")

    plt.xticks(rotation=45)
    plt.yticks()

    plt.grid()
    plt.show()