Hi!
I need to create one file with one graph for each distinct value in a table.
When I create one graph manually, it works fine. However, when I try to do all of them by looping through observations, the files are created empty.
Below is both the code that works and the one that doesn't work
Any ideas?? Thanks a lot!!
# Create sample dataset
library(ggplot2)
groupID<- c("QI1", "QI1", "QI2", "QI2", "QI3", "QI3")
type <- c("Cash", "Equity", "Renta Fija", "Cash", "Equity", "Cash")
share<- c(0.4, 0.6, 0.2, 0.8, 0.7, 0.3)
portfolio <- data.frame (groupID, type, share)
groupFactor = unique(portfolio$groupID)
groupVector = as.character(groupFactor)
# Method 1: only one file. It works. The groupID is hardcoded (QI1)
filename = paste("z:/rendimiento/piechart/","QI1",".jpeg",sep="")
account = portfolio[groupID=="QI1",]
barchart <- ggplot(account, aes(x="", y=share, fill=type)) + geom_bar(width = 1, stat = "identity")
pie <- barchart + coord_polar("y", start=0)
jpeg(file=filename, width=1024, height=1024, units="px")
pie
dev.off()
# Method 2: Loop through groups and create one file for each. It doesn't work
for (gru in groupVector) {
filename = paste("z:/rendimiento/piechart/group",gru,".jpeg",sep="")
account = portfolio[groupID==gru,]
print(account)
barchart <- ggplot(account, aes(x="", y=share, fill=type)) + geom_bar(width = 1, stat = "identity")
pie <- barchart + coord_polar("y", start=0)
jpeg(file=filename, width=1024, height=1024, units="px")
pie
dev.off()
}