1

I am having problems saving annotated ggplot as a png file.

For example from: 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)

I then tried to save the annotated chart as:

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

but this did not work.

I also tried:

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

g
print(g)

dev.off()

but this also did not work.

I would be grateful for some help on what I am doing wrong.

Community
  • 1
  • 1
adam.888
  • 7,686
  • 17
  • 70
  • 105
  • 1
    `ggsave` needs its arguments in a different order, or named: `ggsave(filename="gtest.png", plot=g)`. – bdemarest Mar 17 '14 at 18:20
  • See http://stackoverflow.com/questions/18406991/saving-a-graph-with-ggsave-after-using-ggplot-build-and-ggplot-gtable/ – PatrickT Dec 28 '14 at 13:19

2 Answers2

9

This worked for me with your example code

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

I use it regularly for saving plots not just for ggplot2

TooTone
  • 7,129
  • 5
  • 34
  • 60
2

It looks like there is an error in your ggsave() line:

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

The syntax for the ggsave() command is:

ggsave( filename, plot = last_plot(), device = NULL, path = NULL, scale = 1, width = NA, height = NA, units = c("in", "cm", "mm"), dpi = 300, limitsize = TRUE, ... )

So your command should have been

ggsave(plot=g, filename="gtest.png", width=4, height=4)
altabq
  • 1,322
  • 1
  • 20
  • 33