Files with graphs are created empty.

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()
}

I think your code is not working because you are filtering wrong, it should be
account <- portfolio[portfolio$groupID==gru,]
Anyways, here is another way to do it using purrr package instead of loops and ggsave() instead of a graphics device.

library(dplyr)
library(ggplot2)
library(purrr)

portfolio <- data.frame(stringsAsFactors = FALSE,
                        share = c(0.4, 0.6, 0.2, 0.8, 0.7, 0.3),
                        groupID = c("QI1", "QI1", "QI2", "QI2", "QI3", "QI3"),
                        type = c("Cash", "Equity", "Renta Fija", "Cash", "Equity", "Cash")
                        )
pie_chart <- function(df, group) {
  filename <- paste0(group,".jpeg")
  account <- df %>% filter(groupID == group)
  pie <- account %>% 
    ggplot(aes(x="", y=share, fill=type)) +
    geom_bar(width = 1, stat = "identity") +
    coord_polar("y", start=0)
  ggsave(filename = filename, plot = pie, device = "jpeg", width = 4, height = 4, dpi = 300)
}

walk(unique(portfolio$groupID), ~pie_chart(portfolio, .x))
2 Likes

Thanks a lot!! Your code works perfectly

Not sure why my code doesn't work yet. I tried changing the filtering to

account <- portfolio[portfolio$groupID==gru,]

But it still doesn't work

Thanks again!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.