Ejemplo n.º 1
0
def print_my_plots(r, rplots, out='', file_type='pdf'):
    """
    saves our plots to files named with the plotting method used.
    
    :param r:       pointer to the R instance
    :param rplots:  the ``Bunch`` object where we stored our plots
    :param out:  a base directory to add to our saved plots into
    :param file_type:  the type of output file to use, choices: ['pdf','jpeg','png','ps']
    """
    out = out.rstrip('/')
    
    mkdirp(out)
    
    for plot_id in rplots:
        file_path = "%s/%s.%s" % (out,plot_id,file_type)
        r.ggsave(filename=file_path,plot=rplots[plot_id])
Ejemplo n.º 2
0
def KM(OS, Censored, as_group, data, ggsave=False, path="./", pvalue=0):
    # 分组
    surv_data = data[[OS, Censored, as_group]].sort_values(by=[as_group])
    surv_data["group"] = "L"
    surv_data.iloc[int(surv_data.shape[0] / 2):]["group"] = "H"
    # Kaplan-Meier生存曲线
    with localconverter(ro.default_converter + pandas2ri.converter):
        robjects.globalenv["surv_data"] = pandas2ri.py2rpy(surv_data)
    robjects.globalenv["surv_diff"] = r(
        f"survdiff(Surv({OS}, {Censored})~group,surv_data,rho = 0)")
    Pvalue = r("1 - pchisq(surv_diff$chisq, length(surv_diff$n) -1)")[0]
    if ggsave and Pvalue < pvalue:
        r.ggsave(r(
            f"autoplot(survfit(Surv({OS}, {Censored})~group,surv_data), xlab = 'Time', ylab = 'Survival')+ggtitle('Pvalue = {Pvalue}')"
        ),
                 file=f"{path}/{gene}.pdf")
    return Pvalue
Ejemplo n.º 3
0
    def collect(self, blocks, figure_key="", subfig=0):
        '''collect one or more R figures.

        Plots are collected from all active devices.
        Plots are also collected from result-blocks
        containing a 'ggplot' attribute.

        1. save as png, hires-png and pdf
        2. save thumbnail
        3. insert rendering code at placeholders in output

        returns a map of place holder to placeholder text.
        '''
        # disable plotting if no rpy installed
        if R is None:
            return {}

        map_figure2text = {}

        # determine the image formats to create
        default_format, additional_formats = Utils.getImageFormats(
            self.display_options)
        all_formats = [default_format, ] + additional_formats
        image_options = Utils.getImageOptions(self.display_options)

        ##########################################
        ##########################################
        ##########################################
        # iterate over devices
        devices = R["dev.list"]()
        try:
            maxid = max(R["dev.list"]())
        except TypeError:
            maxid = 0

        for figid in range(2, maxid + 1):

            for id, format, dpi in all_formats:

                R["dev.set"](figid)

                outname = "%s_%02d" % (self.template_name, figid)
                outpath = os.path.join(self.outdir, '%s.%s' % (outname, format))

                if format.endswith("png"):
                    # for busy images there is a problem with figure margins
                    # simply increase dpi until it works.
                    R["dev.set"](figid)

                    width = height = 480 * dpi / 80
                    x = 0
                    while 1:
                        try:
                            R["dev.copy"](device=R.png,
                                          filename=outpath,
                                          res=dpi,
                                          width=width,
                                          height=height)
                            R["dev.off"]()
                        except rpy2.rinterface.RRuntimeError:
                            width *= 2
                            height *= 2
                            if x < 5:
                                continue
                        break

                elif format.endswith("svg"):
                    R["dev.copy"](device=R.svg,
                                  filename=outpath)
                    R["dev.off"]()

                elif format.endswith("eps"):
                    R["dev.copy"](device=R.postscript,
                                  paper='special',
                                  width=6,
                                  height=6,
                                  file=outpath,
                                  onefile=True)
                    R["dev.off"]()
                elif format.endswith("pdf"):
                    R["dev.copy"](device=R.pdf,
                                  paper='special',
                                  width=6,
                                  height=6,
                                  file=outpath,
                                  onefile=True)
                    R["dev.off"]()
                else:
                    raise ValueError("format '%s' not supported" % format)

                if not os.path.exists(outpath):
                    continue
                    # raise ValueError("rendering problem: image file was not be created: %s" % outpath)

                if format == 'png':
                    thumbdir = os.path.join(self.outdir, 'thumbnails')
                    try:
                        os.makedirs(thumbdir)
                    except OSError:
                        pass
                    thumbfile = str('%s.png' % os.path.join(thumbdir, outname))
                    captionfile = str(
                        '%s.txt' % os.path.join(thumbdir, outname))
                    if not os.path.exists(thumbfile):
                        # thumbnail only available in matplotlib >= 0.98.4
                        try:
                            figthumb = image.thumbnail(
                                str(outpath), str(thumbfile), scale=0.3)
                        except AttributeError:
                            pass

                    outfile = open(captionfile, "w")
                    outfile.write("\n".join(self.content) + "\n")
                    outfile.close()

                R["dev.off"](figid)

            # create the text element
            rst_output = Utils.buildRstWithImage(outname,
                                                 self.outdir,
                                                 self.rstdir,
                                                 self.builddir,
                                                 self.srcdir,
                                                 additional_formats,
                                                 self.tracker_id,
                                                 self.links,
                                                 self.display_options)

            map_figure2text["#$rpl %i$#" % figid] = rst_output

        figid = maxid
        ##########################################
        ##########################################
        ##########################################
        # iterate over ggplot plots
        for block in blocks:
            if not hasattr(block, "rggplot"):
                continue
            pp = block.rggplot
            figname = block.figname

            outname = "%s_%s" % (self.template_name, figname)

            for id, format, dpi in all_formats:
                outpath = os.path.join(self.outdir, '%s.%s' % (outname, format))

                try:
                    R.ggsave(outpath, plot=pp, dpi=dpi)
                except rpy2.rinterface.RRuntimeError as msg:
                    raise

                # width, height = 3 * dpi, 3 * dpi
                # if format.endswith("png"):
                #     R.png(outpath,
                #            width = width,
                #            height = height)
                # elif format.endswith("svg"):
                #     R.svg(outpath)
                # elif format.endswith("eps"):
                #     R.postscript(outpath)
                # elif format.endswith("pdf"):
                #     R.pdf(outpath)
                # R.plot(pp)
                # R["dev.off"]()

            # create the text element
            rst_output = Utils.buildRstWithImage(outname,
                                                 self.outdir,
                                                 self.rstdir,
                                                 self.builddir,
                                                 self.srcdir,
                                                 additional_formats,
                                                 self.tracker_id,
                                                 self.links,
                                                 self.display_options)

            map_figure2text["#$ggplot %s$#" % figname] = rst_output

        return map_figure2text
Ejemplo n.º 4
0
    ################# 生存分析 #################
    # https://www.jianshu.com/p/4ad9ba730719
    # r('''suppressMessages(library(survival))''')
    importr("survival")
    importr("ggfortify")
    with localconverter(ro.default_converter + pandas2ri.converter):
        # 构建生存对象
        robjects.globalenv["cox_data"] = ro.conversion.py2rpy(
            sample[["Stromal_score", "Stromal_Group", "OS.time",
                    "OS"]].dropna())
    robjects.globalenv["surv"] = r(
        "Surv(time=cox_data$OS.time, event=cox_data$OS)")
    # Kaplan-Meier生存曲线
    KM_Stromal_fit = r("survfit(surv~cox_data$Stromal_Group)")
    r.ggsave(r.autoplot(KM_Stromal_fit), file="KM_Stromal_fit.pdf")
    # Long-rank检验(对数秩和检验)
    print(r("survdiff(surv~cox_data$Stromal_Group,rho = 0)"))
    # 单因素Cox
    print(r("coxph(surv~cox_data$Stromal_score)"))

    ################# 基因差异表达分析 #################
    ## 读取表达矩阵
    with localconverter(ro.default_converter + pandas2ri.converter):
        exprSet_R = ro.conversion.py2rpy(HT_HG_U133A_sample)
    group_list = "-".join(
        list(sample["Stromal_Group"].astype("str").unique())[::-1])
    #exprSet_R = r(f'''read.table("{path}HT_HG_U133A_sample.txt",header=TRUE,sep="\t",row.names="sample")''')
    ## 制作分组矩阵
    design = sample[["Stromal_Group_L",
                     "Stromal_Group_H"]].set_index(sample["ID"])