treetime/treetime.py
def plot_vs_years(tt, step = None, ax=None, confidence=None, ticks=True, **kwargs):
    '''
    Converts branch length to years and plots the time tree on a time axis.

    Parameters
    ----------
     tt : TreeTime object
        A TreeTime instance after a time tree is inferred

     step : int
        Width of shaded boxes indicating blocks of years. Will be inferred if not specified.
        To switch off drawing of boxes, set to 0

     ax : matplotlib axes
        Axes to be used to plot, will create new axis if None

     confidence : tuple, float
        Draw confidence intervals. This assumes that marginal time tree inference was run.
        Confidence intervals are either specified as an interval of the posterior distribution
        like (0.05, 0.95) or as the weight of the maximal posterior region , e.g. 0.9

     **kwargs : dict
        Key word arguments that are passed down to Phylo.draw

    '''
    import matplotlib.pyplot as plt
    tt.branch_length_to_years()
    nleafs = tt.tree.count_terminals()

    if ax is None:
        fig = plt.figure(figsize=(12,10))
        ax = plt.subplot(111)
    else:
        fig = None
    # draw tree
    if "label_func" not in kwargs:
        kwargs["label_func"] = lambda x:x.name if (x.is_terminal() and nleafs<30) else ""
    Phylo.draw(tt.tree, axes=ax, **kwargs)

    offset = tt.tree.root.numdate - tt.tree.root.branch_length
    date_range = np.max([n.numdate for n in tt.tree.get_terminals()])-offset

    # estimate year intervals if not explicitly specified
    if step is None or (step>0 and date_range/step>100):
        step = 10**np.floor(np.log10(date_range))
        if date_range/step<2:
            step/=5
        elif date_range/step<5:
            step/=2
        step = max(1.0/12,step)

    # set axis labels
    if step:
        dtick = step
        min_tick = step*(offset//step)
        extra = dtick if dtick<date_range else dtick
        tick_vals = np.arange(min_tick, min_tick+date_range+extra, dtick)
        xticks = tick_vals - offset
    else:
        xticks = ax.get_xticks()
        dtick = xticks[1]-xticks[0]
        shift = offset - dtick*(offset//dtick)
        xticks -= shift
        tick_vals = [x+offset-shift for x in xticks]

    ax.set_xticks(xticks)
    ax.set_xticklabels(map(str, tick_vals))
    ax.set_xlabel('year')
    ax.set_ylabel('')
    ax.set_xlim((0,date_range))

    # put shaded boxes to delineate years
    if step:
        ylim = ax.get_ylim()
        xlim = ax.get_xlim()
        from matplotlib.patches import Rectangle
        for yi,year in enumerate(np.arange(np.floor(tick_vals[0]), tick_vals[-1]+.01, step)):
            pos = year - offset
            r = Rectangle((pos, ylim[1]-5),
                          step, ylim[0]-ylim[1]+10,
                          facecolor=[0.7+0.1*(1+yi%2)] * 3,
                          edgecolor=[1,1,1])
            ax.add_patch(r)
            if year in tick_vals and pos>=xlim[0] and pos<=xlim[1] and ticks:
                label_str = str(step*(year//step)) if step<1 else  str(int(year))
                ax.text(pos,ylim[0]-0.04*(ylim[1]-ylim[0]), label_str,
                        horizontalalignment='center')
        ax.set_axis_off()

    # add confidence intervals to the tree graph -- grey bars
    if confidence:
        tree_layout(tt.tree)
        if not hasattr(tt.tree.root, "marginal_inverse_cdf"):
            print("marginal time tree reconstruction required for confidence intervals")
            return ttconf.ERROR
        elif type(confidence) is float:
            cfunc = tt.get_max_posterior_region
        elif len(confidence)==2:
            cfunc = tt.get_confidence_interval
        else:
            print("confidence needs to be either a float (for max posterior region) or a two numbers specifying lower and upper bounds")
            return ttconf.ERROR

        for n in tt.tree.find_clades():
            pos = cfunc(n, confidence)
            ax.plot(pos-offset, np.ones(len(pos))*n.ypos, lw=3, c=(0.5,0.5,0.5))
    return fig, ax
def plot_vs_years(tt, step = None, ax=None, confidence=None, ticks=True, **kwargs):
    '''
    Converts branch length to years and plots the time tree on a time axis.

    Parameters
    ----------
     tt : TreeTime object
        A TreeTime instance after a time tree is inferred

     step : int
        Width of shaded boxes indicating blocks of years. Will be inferred if not specified.
        To switch off drawing of boxes, set to 0

     ax : matplotlib axes
        Axes to be used to plot, will create new axis if None

     confidence : tuple, float
        Draw confidence intervals. This assumes that marginal time tree inference was run.
        Confidence intervals are either specified as an interval of the posterior distribution
        like (0.05, 0.95) or as the weight of the maximal posterior region , e.g. 0.9

     **kwargs : dict
        Key word arguments that are passed down to Phylo.draw

    '''
    import matplotlib.pyplot as plt
    tt.branch_length_to_years()
    nleafs = tt.tree.count_terminals()

    if ax is None:
        fig = plt.figure(figsize=(12,10))
        ax = plt.subplot(111)
    else:
        fig = None
    # draw tree
    if "label_func" not in kwargs:
        kwargs["label_func"] = lambda x:x.name if (x.is_terminal() and nleafs<30) else ""
    Phylo.draw(tt.tree, axes=ax, **kwargs)

    offset = tt.tree.root.numdate - tt.tree.root.branch_length
    date_range = np.max([n.numdate for n in tt.tree.get_terminals()])-offset

    # estimate year intervals if not explicitly specified
    if step is None or (step>0 and date_range/step>100):
        step = 10**np.floor(np.log10(date_range))
        if date_range/step<2:
            step/=5
        elif date_range/step<5:
            step/=2
        step = max(1.0/12,step)

    # set axis labels
    if step:
        dtick = step
        min_tick = step*(offset//step)
        extra = dtick if dtick<date_range else dtick
        tick_vals = np.arange(min_tick, min_tick+date_range+extra, dtick)
        xticks = tick_vals - offset
    else:
        xticks = ax.get_xticks()
        dtick = xticks[1]-xticks[0]
        shift = offset - dtick*(offset//dtick)
        xticks -= shift
        tick_vals = [x+offset-shift for x in xticks]

    ax.set_xticks(xticks)
    ax.set_xticklabels(map(str, tick_vals))
    ax.set_xlabel('year')
    ax.set_ylabel('')
    ax.set_xlim((0,date_range))

    # put shaded boxes to delineate years
    if step:
        ylim = ax.get_ylim()
        xlim = ax.get_xlim()
        from matplotlib.patches import Rectangle
        for yi,year in enumerate(np.arange(np.floor(tick_vals[0]), tick_vals[-1]+.01, step)):
            pos = year - offset
            r = Rectangle((pos, ylim[1]-5),
                          step, ylim[0]-ylim[1]+10,
                          facecolor=[0.7+0.1*(1+yi%2)] * 3,
                          edgecolor=[1,1,1])
            ax.add_patch(r)
            if year in tick_vals and pos>=xlim[0] and pos<=xlim[1] and ticks:
                label_str = str(step*(year//step)) if step<1 else  str(int(year))
                ax.text(pos,ylim[0]-0.04*(ylim[1]-ylim[0]), label_str,
                        horizontalalignment='center')
        ax.set_axis_off()

    # add confidence intervals to the tree graph -- grey bars
    if confidence:
        tree_layout(tt.tree)
        if not hasattr(tt.tree.root, "marginal_inverse_cdf"):
            print("marginal time tree reconstruction required for confidence intervals")
            return ttconf.ERROR
        elif type(confidence) is float:
            cfunc = tt.get_max_posterior_region
        elif len(confidence)==2:
            cfunc = tt.get_confidence_interval
        else:
            print("confidence needs to be either a float (for max posterior region) or a two numbers specifying lower and upper bounds")
            return ttconf.ERROR

        for n in tt.tree.find_clades():
            pos = cfunc(n, confidence)
            ax.plot(pos-offset, np.ones(len(pos))*n.ypos, lw=3, c=(0.5,0.5,0.5))
    return fig, ax
def plot_vs_years ( tt , step = None , ax = None , confidence = None , ticks = True , * * kwargs ) : import matplotlib . pyplot as plt tt . branch_length_to_years ( ) nleafs = tt . tree . count_terminals ( ) if ax is None : fig = plt . figure ( figsize = ( 12 , 10 ) ) ax = plt . subplot ( 111 ) else : fig = None # draw tree if "label_func" not in kwargs : kwargs [ "label_func" ] = lambda x : x . name if ( x . is_terminal ( ) and nleafs < 30 ) else "" Phylo . draw ( tt . tree , axes = ax , * * kwargs ) offset = tt . tree . root . numdate - tt . tree . root . branch_length date_range = np . max ( [ n . numdate for n in tt . tree . get_terminals ( ) ] ) - offset # estimate year intervals if not explicitly specified if step is None or ( step > 0 and date_range / step > 100 ) : step = 10 ** np . floor ( np . log10 ( date_range ) ) if date_range / step < 2 : step /= 5 elif date_range / step < 5 : step /= 2 step = max ( 1.0 / 12 , step ) # set axis labels if step : dtick = step min_tick = step * ( offset // step ) extra = dtick if dtick < date_range else dtick tick_vals = np . arange ( min_tick , min_tick + date_range + extra , dtick ) xticks = tick_vals - offset else : xticks = ax . get_xticks ( ) dtick = xticks [ 1 ] - xticks [ 0 ] shift = offset - dtick * ( offset // dtick ) xticks -= shift tick_vals = [ x + offset - shift for x in xticks ] ax . set_xticks ( xticks ) ax . set_xticklabels ( map ( str , tick_vals ) ) ax . set_xlabel ( 'year' ) ax . set_ylabel ( '' ) ax . set_xlim ( ( 0 , date_range ) ) # put shaded boxes to delineate years if step : ylim = ax . get_ylim ( ) xlim = ax . get_xlim ( ) from matplotlib . patches import Rectangle for yi , year in enumerate ( np . arange ( np . floor ( tick_vals [ 0 ] ) , tick_vals [ - 1 ] + .01 , step ) ) : pos = year - offset r = Rectangle ( ( pos , ylim [ 1 ] - 5 ) , step , ylim [ 0 ] - ylim [ 1 ] + 10 , facecolor = [ 0.7 + 0.1 * ( 1 + yi % 2 ) ] * 3 , edgecolor = [ 1 , 1 , 1 ] ) ax . add_patch ( r ) if year in tick_vals and pos >= xlim [ 0 ] and pos <= xlim [ 1 ] and ticks : label_str = str ( step * ( year // step ) ) if step < 1 else str ( int ( year ) ) ax . text ( pos , ylim [ 0 ] - 0.04 * ( ylim [ 1 ] - ylim [ 0 ] ) , label_str , horizontalalignment = 'center' ) ax . set_axis_off ( ) # add confidence intervals to the tree graph -- grey bars if confidence : tree_layout ( tt . tree ) if not hasattr ( tt . tree . root , "marginal_inverse_cdf" ) : print ( "marginal time tree reconstruction required for confidence intervals" ) return ttconf . ERROR elif type ( confidence ) is float : cfunc = tt . get_max_posterior_region elif len ( confidence ) == 2 : cfunc = tt . get_confidence_interval else : print ( "confidence needs to be either a float (for max posterior region) or a two numbers specifying lower and upper bounds" ) return ttconf . ERROR for n in tt . tree . find_clades ( ) : pos = cfunc ( n , confidence ) ax . plot ( pos - offset , np . ones ( len ( pos ) ) * n . ypos , lw = 3 , c = ( 0.5 , 0.5 , 0.5 ) ) return fig , ax
Converts branch length to years and plots the time tree on a time axis.

    Parameters
    ----------
     tt : TreeTime object
        A TreeTime instance after a time tree is inferred

     step : int
        Width of shaded boxes indicating blocks of years. Will be inferred if not specified.
        To switch off drawing of boxes, set to 0

     ax : matplotlib axes
        Axes to be used to plot, will create new axis if None

     confidence : tuple, float
        Draw confidence intervals. This assumes that marginal time tree inference was run.
        Confidence intervals are either specified as an interval of the posterior distribution
        like (0.05, 0.95) or as the weight of the maximal posterior region , e.g. 0.9

     **kwargs : dict
        Key word arguments that are passed down to Phylo.draw
Converts branch length to years and plots the time tree on a time axis .