Beispiel #1
0
def plot(out,
         fontsize=12,
         savepath='',
         width=10,
         height=6,
         cmap='Set1',
         cii_alpha=0.05,
         cii_lines='dense',
         methodtype='lifeline',
         title='Survival function',
         full_ylim=False,
         y_percentage=False):
    """Make plot.

    Parameters
    ----------
    out : dict
        Results from the fit function.
    fontsize : int, optional
        Font size for the graph. The default is 12.
    savepath : String, optional
        Path to store the figure. The default is ''.
    width : int, optional
        Width of the figure. The default is 10.
    height : int, optional
        height of the figure. The default is 6.
    cmap : String, optional
        Specify your own colors for each class-label or use a colormap:  https://matplotlib.org/examples/color/colormaps_reference.html. The default is 'Set1'.
        [(1, 0, 0),(0, 0, 1),(..)]
        'Set1'       (default)
        'Set2'       Discrete colors
        'Pastel1'    Discrete colors
        'Paired'     Discrete colors
        'rainbow'
        'bwr'        Blue-white-red
        'binary' or 'binary_r'
        'seismic'    Blue-white-red
        'Blues'      white-to-blue
        'Reds'       white-to-red
    cii_alpha : float, optional
        Confidence interval (works only when methodtype='lifelines'). The default is 0.05.
    cii_lines : String, optional
        Confidence lines (works only when methodtype='lifelines'). The default is 'dense'.
        'lifelines' (default)
        'custom'
    methodtype : String, optional
        Implementation type. The default is 'lifeline'.
        'dense'   (dense/filled lines)
        'line'
         None  (no lines)
    title : TYPE, optional
        DESCRIPTION. The default is 'Survival function'.

    Returns
    -------
    None.

    """
    KMcoord = {}
    Param = {}
    Param['width'] = width
    Param['height'] = height
    Param['fontsize'] = fontsize
    Param['savepath'] = savepath
    labx = out['labx']

    # Combine data and gather class labels
    data = np.vstack((out['time_event'], out['censoring'])).T

    # Make colors and legend-names for class-labels
    [class_colors, classlabel] = make_class_color_names(data,
                                                        out['labx'],
                                                        out['uilabx'],
                                                        cmap=cmap)

    if methodtype == 'lifeline':
        # Init
        kmf_all = []

        # Startup figure
        fig = plt.figure(figsize=(Param['width'], Param['height']))
        ax = fig.add_subplot(111)
        if full_ylim:
            ax.set_ylim([0.0, 1.05])
        if y_percentage:
            ax.yaxis.set_major_formatter(PercentFormatter(1.0))
        if out['logrank'] != []:
            plt.title('%s, Logrank Test P-Value = %.5f' %
                      (title, out['logrank_P']))

        # Compute KM survival coordinates per class
        if cii_lines == 'dense':
            cii_lines = False
        if cii_lines == 'line':
            cii_lines = True
        if cii_lines == '' or cii_lines == None or cii_alpha == None:
            cii_lines = False
            cii_alpha = 0

        for i in range(0, len(out['uilabx'])):
            kmf = KaplanMeierFitter()
            idx = np.where(labx == out['uilabx'][i])[0]
            # Fit
            kmf.fit(out['time_event'][idx],
                    event_observed=out['censoring'][idx],
                    label=classlabel[i],
                    ci_labels=None,
                    alpha=(1 - cii_alpha))
            # Plot
            kmf.plot(ax=ax,
                     ci_force_lines=cii_lines,
                     color=class_colors[i],
                     show_censors=True)
            # Store
            kmf_all.append(
                kmf.fit(out['time_event'][idx],
                        event_observed=out['censoring'][idx],
                        label=classlabel[i],
                        ci_labels=None,
                        alpha=(1 - cii_alpha)))

        add_at_risk_counts(*kmf_all, ax=ax)

        ax.tick_params(axis='x',
                       length=15,
                       width=1,
                       direction='out',
                       labelsize=Param['fontsize'])
        ax.tick_params(axis='y',
                       length=15,
                       width=1,
                       direction='out',
                       labelsize=Param['fontsize'])
        ax.spines['bottom'].set_position(['outward', Param['fontsize']])
        ax.spines['left'].set_position(['outward', Param['fontsize']])
        #    ax.rc('font', size= Param['fontsize'])   # controls default text sizes
        #    ax.rc('axes',  labelsize = Param['fontsize'])  # fontsize of the x and y labels

        if Param['savepath'] != '':
            savefig(fig, Param['savepath'])

    if methodtype == 'custom':
        # Compute KM survival coordinates per class
        for i in range(0, len(out['uilabx'])):
            idx = np.where(labx == out['uilabx'][i])[0]
            tmpdata = data[idx, :].tolist()
            KMcoord[i] = compute_coord(tmpdata)

        # Plot KM survival lines
        plotkm(KMcoord,
               classlabel,
               cmap=class_colors,
               width=Param['width'],
               height=Param['height'],
               fontsize=Param['fontsize'])
Beispiel #2
0
def plot(out,
         fontsize=12,
         savepath='',
         width=10,
         height=6,
         cmap='Set1',
         cii_alpha=0.05,
         cii_lines='dense',
         methodtype='lifeline',
         title='Survival function'):
    '''
    

    Parameters
    ----------
    out :       [dict] Dictionary derived from the fit function.

    fontsize :  [INT],  Font size for the graph
                default is 12.
    
    savepath:   [STRING], Path to store the figure

    width:      [INT], Width of the figure
                10 (default)
                
    height:     [INT], Width of the figure
                6 (default)

    cmap:       [STRING], Specify your own colors for each class-label or use a colormap:  https://matplotlib.org/examples/color/colormaps_reference.html
                [(1, 0, 0),(0, 0, 1),(..)]
                'Set1'       (default)     
                'Set2'       Discrete colors
                'Pastel1'    Discrete colors
                'Paired'     Discrete colors
                'rainbow'
                'bwr'        Blue-white-red
                'binary' or 'binary_r'
                'seismic'    Blue-white-red 
                'Blues'      white-to-blue
                'Reds'       white-to-red

    cii_alpha:  [FLOAT], Confidence interval (works only when methodtype='lifelines')
                0.05 (default)
                
    cii_lines:  [STRING], Confidence lines (works only when methodtype='lifelines')
                'lifelines' (default)
                'custom'

    methodtype:  [STRING], Implementation type
                 'dense'   (dense/filled lines)
                 'line' 
                  None  (no lines)

    Returns
    -------
    None.

    '''
    KMcoord = {}
    Param = {}
    Param['width'] = width
    Param['height'] = height
    Param['fontsize'] = fontsize
    Param['savepath'] = savepath
    labx = out['labx']

    # Combine data and gather class labels
    data = np.vstack((out['time_event'], out['censoring'])).T

    # Make colors and legend-names for class-labels
    [class_colors, classlabel] = make_class_color_names(data,
                                                        out['labx'],
                                                        out['uilabx'],
                                                        cmap=cmap)

    if methodtype == 'lifeline':
        # Init
        kmf_all = []

        # Startup figure
        fig = plt.figure(figsize=(Param['width'], Param['height']))
        ax = fig.add_subplot(111)
        #        ax.grid(True)
        #        ax.ylabel('Percentage survival')
        if out['logrank'] != []:
            plt.title('%s, Logrank Test P-Value = %.5f' %
                      (title, out['logrank_P']))

        # Compute KM survival coordinates per class
        if cii_lines == 'dense':
            cii_lines = False
        if cii_lines == 'line':
            cii_lines = True
        if cii_lines == '' or cii_lines == None or cii_alpha == None:
            cii_lines = False
            cii_alpha = 0

        for i in range(0, len(out['uilabx'])):
            kmf = KaplanMeierFitter()
            idx = np.where(labx == out['uilabx'][i])[0]
            # Fit
            kmf.fit(out['time_event'][idx],
                    event_observed=out['censoring'][idx],
                    label=classlabel[i],
                    ci_labels=None,
                    alpha=1 - cii_alpha)
            # Plot
            kmf.plot(ax=ax,
                     ci_force_lines=cii_lines,
                     color=class_colors[i],
                     show_censors=True)
            # Store
            kmf_all.append(
                kmf.fit(out['time_event'][idx],
                        event_observed=out['censoring'][idx],
                        label=classlabel[i],
                        ci_labels=None,
                        alpha=1 - cii_alpha))

        if len(kmf_all) == 1:
            add_at_risk_counts(kmf_all[0], ax=ax)
        elif len(kmf_all) == 2:
            add_at_risk_counts(kmf_all[0], kmf_all[1], ax=ax)
        elif len(kmf_all) == 3:
            add_at_risk_counts(kmf_all[0], kmf_all[1], kmf_all[2], ax=ax)
        elif len(kmf_all) == 4:
            add_at_risk_counts(kmf_all[0],
                               kmf_all[1],
                               kmf_all[2],
                               kmf_all[3],
                               ax=ax)
        elif len(kmf_all) == 5:
            add_at_risk_counts(kmf_all[0],
                               kmf_all[1],
                               kmf_all[2],
                               kmf_all[3],
                               kmf_all[4],
                               ax=ax)
        elif len(kmf_all) == 6:
            add_at_risk_counts(kmf_all[0],
                               kmf_all[1],
                               kmf_all[2],
                               kmf_all[3],
                               kmf_all[4],
                               kmf_all[5],
                               ax=ax)
        elif len(kmf_all) == 7:
            add_at_risk_counts(kmf_all[0],
                               kmf_all[1],
                               kmf_all[2],
                               kmf_all[3],
                               kmf_all[4],
                               kmf_all[5],
                               kmf_all[6],
                               ax=ax)
        elif len(kmf_all) == 8:
            add_at_risk_counts(kmf_all[0],
                               kmf_all[1],
                               kmf_all[2],
                               kmf_all[3],
                               kmf_all[4],
                               kmf_all[5],
                               kmf_all[6],
                               kmf_all[7],
                               ax=ax)
        elif len(kmf_all) == 9:
            add_at_risk_counts(kmf_all[0],
                               kmf_all[1],
                               kmf_all[2],
                               kmf_all[3],
                               kmf_all[4],
                               kmf_all[5],
                               kmf_all[6],
                               kmf_all[7],
                               kmf_all[8],
                               ax=ax)
        elif len(kmf_all) == 10:
            add_at_risk_counts(kmf_all[0],
                               kmf_all[1],
                               kmf_all[2],
                               kmf_all[3],
                               kmf_all[4],
                               kmf_all[5],
                               kmf_all[6],
                               kmf_all[7],
                               kmf_all[8],
                               kmf_all[9],
                               ax=ax)
        else:
            print('[KM] Maximum of 10 classes is reached.')

        ax.tick_params(axis='x',
                       length=15,
                       width=1,
                       direction='out',
                       labelsize=Param['fontsize'])
        ax.tick_params(axis='y',
                       length=15,
                       width=1,
                       direction='out',
                       labelsize=Param['fontsize'])
        ax.spines['bottom'].set_position(['outward', Param['fontsize']])
        ax.spines['left'].set_position(['outward', Param['fontsize']])
        #    ax.rc('font', size= Param['fontsize'])   # controls default text sizes
        #    ax.rc('axes',  labelsize = Param['fontsize'])  # fontsize of the x and y labels

        if Param['savepath'] != '':
            savefig(fig, Param['savepath'])

    if methodtype == 'custom':
        # Compute KM survival coordinates per class
        for i in range(0, len(out['uilabx'])):
            idx = np.where(labx == out['uilabx'][i])[0]
            tmpdata = data[idx, :].tolist()
            KMcoord[i] = compute_coord(tmpdata)

        # Plot KM survival lines
        plotkm(KMcoord,
               classlabel,
               cmap=class_colors,
               width=Param['width'],
               height=Param['height'],
               fontsize=Param['fontsize'])