5.4 Add a graph

First, create an image out of a graph.

# Prepare object
currencies <- names(swissfranc)[-1]
gcurr <- reshape(swissfranc, 
                 varying = currencies, 
                 direction = "long", 
                 v.names = "Value", 
                 times = currencies, 
                 timevar = "Currency")

# Use ggplot2 to create a graph
require(ggplot2)
p <- ggplot(gcurr, aes(Date, Value, colour = Currency)) +
  geom_line() + stat_smooth(method = "loess") +
  scale_y_continuous("Exchange Rate CHF/Curr") +
  labs(title = paste0("CHF vs ", paste(currencies, collapse = ", ")), x = "") + 
  theme(axis.title.y = element_text(size = 10, angle = 90, vjust = 0.3))
print(p)

# Save plot to as a png
dev.copy(png, "xlconnect-demo/swissfrancplot.png")
dev.off()

Then, add the image to the output file.

# Define the location in the output file
createName(wb, name = "graph", formula = "NamedRegionEx!$H$2")

# Add image to the file
addImage(wb, 
         filename = "xlconnect-demo/swissfrancplot.png", 
         name = "graph", 
         originalSize = TRUE)

# Save workbook - this actually writes the file
saveWorkbook(wb)