I'm working with google analytics data. I have 100 different google analytics campaigns and I have to make a graph for each of them, clearly I can't use facet_grid or wrap due to the number of campaigns.
So I need to make a graph using only the data from one campaign, then save the png of it and make a new graph of another campaign and save the png, and so on.
The code of graphs is:
ggplot(Data%>%filter(Cost < 2000000, Impressions < 400000, Campaign == "CAMPAIGN 1"),
aes( x = Cost, color = CTR, y = Conversions, size = Impressions, shape = Week))
geom_point()
scale_size(range = c(0, 10))
geom_smooth(se = F, show.legend = F, method = "lm")
labs(title = "Daily Conversions CAMPAIGN 1",
shape = "")
theme_bw()
scale_color_viridis_b()
I need that in the filter function and in labs change the filter of the campaign and the title, later save the graph in a png with the name of the Campaign.
I know that with a for function it can work but I don't know how to make it do the graph for each of the campaigns.
Thanks in advance
CodePudding user response:
What about this?
for (i in 1:5) {
name <- paste("Campaign", i)
plot <- ggplot(Data%>%filter(Cost < 2000000, Impressions < 400000, Campaign == name),
aes( x = Cost, color = CTR, y = Conversions, size = Impressions, shape = Week))
geom_point()
scale_size(range = c(0, 10))
geom_smooth(se = F, show.legend = F, method = "lm")
labs(title = "Daily Conversions CAMPAIGN 1",
shape = "")
theme_bw()
scale_color_viridis_b()
ggsave(plot, paste0("./", name, ".png"))
}
CodePudding user response:
Consider by
, object-oriented wrapper to tapply
, that allows you to slice a data frame by factor(s) and run processes on the subsets to return a simplified object (i.e., vector, matrix), or a list of any output:
build_plot <- function(sub) {
plt <- ggplot(filter(sub, Cost < 2000000, Impressions < 400000),
aes(x = Cost, color = CTR, y = Conversions, size = Impressions, shape = Week))
geom_point()
scale_size(range = c(0, 10))
geom_smooth(se = FALSE, show.legend = FALSE, method = "lm")
labs(title = paste("Daily Conversions", sub$Campaign[1]), shape = "")
theme_bw()
scale_color_viridis_b()
ggsave(plot=plt, filename=paste0(sub$Campaign[1], ".png"), units="in", width=12, height=8)
return(plt)
}
plot_list <- by(Data, Data$Campaign, build_plot)
CodePudding user response:
At the end, i wrote this code and work fine:
List <- c(unique(Data$`Campaign name`))
List
plot_list = list()
for (i in 1:100) {
p = ggplot(Data%>%filter(`Campaign name` == List[i]), aes(x=Cost, y=Conversions)) geom_point()
labs(title = "Conversiones Diarias según Inversión",
subtitle = List[i])
plot_list[[i]] = p
ggsave(plot_list[[i]], file=paste0("plot_", i,".png"), width = 32, height = 25, units = "cm")
}
Another option without ggsave part in for loop is run this for loop after:
pdf("plots.pdf")
for (i in 1:100) {
print(plot_list[[i]])
}
dev.off()