简体   繁体   中英

How to display a heatmap created in python using rpy2?

I am currently trying to generate a heatmap in python from a text file, using R commands (with rpy2). It works fine in R, but when I take it to python, the Quartz interface displays quickly and then closes. I would like either to be able to save the quartz display to a file, or directly save my heatmap to a file without displaying it.

Here is the code I have been using:

import rpy2.robjects as robjects 

robjects.r('''
library("gplots")
data = read.csv("/Users/.../Heatmap_data.txt")
DF = data.frame(data)
MD = data.matrix(DF,rownames.force=NA)
heatmap.2(MD, scale="none", col=redgreen(100), cexRow=0.1, key=FALSE, symkey=FALSE, trace="none", Colv=FALSE)
''')

I'm using python 2.7, on OS X Yosemite. Thank you for any help.

import numpy as np
import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
ro.numpy2ri.activate() 
R = ro.r

data = np.random.random((10, 10))
R.png(file='/tmp/out.png')
R.heatmap(data)
R("dev.off()")

writes to the file /tmp/out.png without displaying the image:

在此处输入图片说明 .


Preventing the displayed image from immediately closing can be done like this:

script.py:

import numpy as np
import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
import rpy2.rinterface as rinterface
import time
import threading

ro.numpy2ri.activate() 
R = ro.r

def ion():
    def r_refresh(interval = 0.03):
        while True:
            rinterface.process_revents()
            time.sleep(interval)
    t = threading.Thread(target=r_refresh)
    t.daemon = True
    t.start()

ion()
data = np.random.random((10, 10))
R.heatmap(data)

R("dev.copy(png,'/tmp/out2.png')")
R("dev.off()")
try:
    # for Python2
    raw_input()
except NameError:
    # for Python3
    input()

The raw_input or input call prevents the Python interpreter from exiting, thus allowing the window to stay open, until the user presses Enter.

The ion function calls rinterface.process_revents() periodically so the displayed window will react to GUI events such as resizing or being closed.

dev.copy(png,'/tmp/out2.png') saves the already-displayed image to a file .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM