【问题标题】:R Saving an annotated ggplot as a png fileR将带注释的ggplot保存为png文件
【发布时间】:2014-03-17 18:06:24
【问题描述】:

我在将带注释的 ggplot 保存为 png 文件时遇到问题。

例如来自: How to place grobs with annotation_custom() at precise areas of the plot region?

library(gtable)
library(ggplot2)
library(plyr) 
set.seed(1)
d <- data.frame(x=rep(1:10, 5),
            y=rnorm(50),
            g = gl(5,10))

# example plot
p <- ggplot(d, aes(x,y,colour=g)) +
  geom_line() +
  scale_x_continuous(expand=c(0,0))+
  theme(legend.position="top",
    plot.margin=unit(c(1,0,0,0),"line"))

# dummy data for the legend plot
# built with the same y axis (same limits, same expand factor)
d2 <- ddply(d, "g", summarise, x=0, y=y[length(y)])
d2$lab <- paste0("line #", seq_len(nrow(d2)))

plegend <- ggplot(d, aes(x,y, colour=g)) +
  geom_blank() +
  geom_segment(data=d2, aes(x=2, xend=0, y=y, yend=y), 
           arrow=arrow(length=unit(2,"mm"), type="closed")) +
  geom_text(data=d2, aes(x=2.5,label=lab), hjust=0) +
  scale_x_continuous(expand=c(0,0)) +
  guides(colour="none")+
  theme_minimal() + theme(line=element_blank(),
                      text=element_blank(),
                      panel.background=element_rect(fill="grey95", linetype=2))

  # extract the panel only, we don't need the rest
gl <- gtable_filter(ggplotGrob(plegend), "panel")

# add a cell next to the main plot panel, and insert gl there
g <- ggplotGrob(p)
index <- subset(g$layout, name == "panel")
g <- gtable_add_cols(g, unit(1, "strwidth", "line # 1") + unit(1, "cm"))
g <- gtable_add_grob(g, gl, t = index$t, l=ncol(g), 
                 b=index$b, r=ncol(g))
grid.newpage()
grid.draw(g)

然后我尝试将带注释的图表保存为:

ggsave(g, file="gtest.png" , width=4, height=4)

但这不起作用。

我也试过了:

png(paste("gtest1.png"), width = 800, height = 500)

g
print(g)

dev.off()

但这也没有用。

如果我做错了什么,我将不胜感激。

【问题讨论】:

标签: r


【解决方案1】:

你的示例代码对我有用

dev.print(file="test.png", device=png, width=800)

我经常使用它来保存绘图,而不仅仅是ggplot2

【讨论】:

  • 非常感谢您的帮助
【解决方案2】:

您的ggsave() 行中似乎有错误:

ggsave(g, file="gtest.png" , width=4, height=4)

ggsave() 命令的语法是:

ggsave( 文件名, 情节 = last_plot(), 设备=空, 路径=空, 比例 = 1, 宽度 = NA, 高度 = NA, 单位 = c("in", "cm", "mm"), dpi = 300, 限制=真, ... )

所以你的命令应该是

ggsave(plot=g, filename="gtest.png", width=4, height=4)

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 2020-03-09
    • 2022-06-10
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多