获取 R 中以像素为单位的绘图大小
Get size of plot in pixels in R
我正在用 R 生成一个有很多行的热图。
TL;DR 如何在 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")
默认图像适合 window,但我们无法读取行名称。
pheatmap(df,scale="row",cellheight = 10)
更改单元格高度让我们可以读取行名称,但现在图像不适合 window!
在这个例子中,我使用 pheatmap
,但也 运行 与其他绘图生成包一起使用。
虽然我已经开始期待 R 会出现这种令人沮丧的行为,并且通过反复试验可以为情节制作适当大小的图像,但这似乎是我应该能够从程序中获得的东西?
有没有办法自动获取绘图的尺寸,以便我可以为其创建正确大小的 PDF 或 PNG?
函数pheatmap
使用网格图形绘制绘图,并在"bigpts"中指定其元素的大小,其中72 "bigpts" == 1英寸。如果你有很多行并指定合理的行高,这将超过绘图 window.
因为它被指定为gtree
,我们实际上可以访问组件的高度和宽度,并使用它们来设置我们的 png 或 pdf 的尺寸。
此函数将获取地块的总高度和宽度(以英寸为单位),并将它们返回到命名列表中:
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))
}
我们可以使用它来指定绘图设备的尺寸:
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
个对象的解决方案。
我正在用 R 生成一个有很多行的热图。
TL;DR 如何在 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
,但也 运行 与其他绘图生成包一起使用。
虽然我已经开始期待 R 会出现这种令人沮丧的行为,并且通过反复试验可以为情节制作适当大小的图像,但这似乎是我应该能够从程序中获得的东西?
有没有办法自动获取绘图的尺寸,以便我可以为其创建正确大小的 PDF 或 PNG?
函数pheatmap
使用网格图形绘制绘图,并在"bigpts"中指定其元素的大小,其中72 "bigpts" == 1英寸。如果你有很多行并指定合理的行高,这将超过绘图 window.
因为它被指定为gtree
,我们实际上可以访问组件的高度和宽度,并使用它们来设置我们的 png 或 pdf 的尺寸。
此函数将获取地块的总高度和宽度(以英寸为单位),并将它们返回到命名列表中:
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))
}
我们可以使用它来指定绘图设备的尺寸:
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
个对象的解决方案。