获取 R 中的绘图大小(以像素为单位) [英] Get size of plot in pixels in R

查看:118
本文介绍了获取 R 中的绘图大小(以像素为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中生成了一个包含很多行的热图.
TL;DR 如何获得 R 中绘图的实际大小?

I am generating a heatmap in R with lots of rows.
TL;DR how do I get the real size of a plot in R?

df=data.frame(one=1:100,two=101:200,three=201:300)
names=1:100
names=paste0("Cell",names)
rownames(df)=(names)
pheatmap(df,scale="row")

默认图像适合窗口,但我们无法读取行名称.

pheatmap(df,scale="row",cellheight = 10)更改单元格高度可以让我们读取行名称,但现在图像不适合窗口!

在这个例子中,我使用了 pheatmap,但也遇到了其他绘图生成包的问题.

In this example i am using pheatmap, but also run into this stuff with other plot generating packages.

虽然我越来越期待 R 会出现这样令人沮丧的行为,并且通过反复试验可以为情节制作适当大小的图像,但这似乎是我应该能够从程序中获得的东西?

While I've grown to expect frustrating behavior like this from R and by trial and error could make an appropriately size image for the plot, this seems like something that I should be able to get from the program?

有没有办法自动获取绘图的尺寸,以便我可以为其创建正确大小的 PDF 或 PNG?

Is there a way to get the dimensions of the plot automatically so that I can create correctly size PDF or PNG for it?

推荐答案

pheatmap 函数使用网格图形绘制图形,并在bigpts"中指定其元素的大小,其中 72bigpts" == 1 英寸.如果您有很多行并指定了合理的行高,这将超出绘图窗口.

The function pheatmap uses grid graphics to draw its plots, and specifies the size of its elements in "bigpts" where 72 "bigpts" == 1 inch. If you have lots of rows and specify a reasonable row height, this will exceed the plotting window.

因为它被指定为gtree,我们实际上可以访问组件的高度和宽度并使用它们来设置我们的png或pdf的尺寸.

Because it is specified as a gtree, we can actually access the height and width of the components and use them to set the dimensions of our png or pdf.

此函数将获取以英寸为单位的绘图的总高度和宽度,并在命名列表中返回它们:

This function will harvest the total height and width in inches of a plot, returning them in a named list:

get_plot_dims <- function(heat_map)
{
  plot_height <- sum(sapply(heat_map$gtable$heights, grid::convertHeight, "in"))
  plot_width  <- sum(sapply(heat_map$gtable$widths, grid::convertWidth, "in"))
  return(list(height = plot_height, width = plot_width))
}

我们可以使用它来指定绘图设备的尺寸:

We can use this to specify the dimensions of our plotting device:

my_plot <- pheatmap(df,scale="row", cellheight = 10)
plot_dims <- get_plot_dims(my_plot)

png("plot.png", height = plot_dims$height, width = plot_dims$width, units = "in", res = 72)
my_plot
dev.off()

哪个给出了所需的情节

请注意,这不是 R 绘图的通用解决方案,而是特定于 pheatmap 对象.

Note that this is not a general solution for R plots, but specific to pheatmap objects.

这篇关于获取 R 中的绘图大小(以像素为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆