python - 如何使用 rpy2 显示在 python 中创建的热图?

标签 python r quartz-graphics rpy2

我目前正在尝试使用 R 命令(使用 rpy2)从文本文件在 python 中生成热图。它在 R 中运行良好,但是当我将其带到 python 中时,Quartz 界面快速显示然后关闭。我希望能够将 quartz 显示保存到文件中,或者直接将热图保存到文件中而不显示它。

这是我一直在使用的代码:

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)
''')

我在 OS X Yosemite 上使用 python 2.7。 感谢您的帮助。

最佳答案

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 不显示图像:

enter image description here


Preventing the displayed image from immediately closing可以这样做:

脚本.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()

raw_inputinput 调用可防止 Python 解释器退出,从而允许窗口保持打开状态,直到用户按 Enter 键。

ion 函数 calls rinterface.process_revents() periodically所以 显示的窗口将对 GUI 事件使用react,例如调整大小或关闭。

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

关于python - 如何使用 rpy2 显示在 python 中创建的热图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051123/

相关文章:

ios - iOS 中 CGPointApplyAffineTransform 函数的公式

python - Mechanize (将输入设置为表单)

python - 我可以使用以并行方式读取文件的迭代器吗?

python - Pyinstaller 应用程序正在访问 txt 文件,但不写入它们(在应用程序编译之前工作)

r - 将不规则的 x,y 数据点插入到规则网格中以进行轮廓映射

ios - 如何同时绘制到多个 CGLayer?

python - 如何阅读 Jenkins 工作的标志

R采样绕过randomForest 32因子限制

r - 列出 lm 对象,保留它们的类

cocoa-touch - CALayer 和离屏渲染