So I have a big file and I made a looping to calculate the mean and to do the graphic:
for (i in c(25:28)) {
trait <- all_exp_1 %>%
group_by(Experiment,time) %>%
dplyr::summarise(across(i,~data.frame(Mean = mean(.,na.rm=TRUE),
N = length(.),
SD = sd(.,na.rm=TRUE),
Min = min(.,na.rm=TRUE),
Max = max(.,na.rm=TRUE),
Coeff.Variation = sd(., na.rm=TRUE)/mean(., na.rm=TRUE)*100))) %>%
pivot_longer(-maturacao & -Experimento) %>% ungroup()
file_name = paste("files/plot_",trait[[3]][[1]], ".tiff", sep="")
tiff(file=file_name, width =6 , height = 4, units = 'in', res = 200)
ggplot(trait,aes(x = maturacao, y =trait$value[[1]], fill = factor(Experimento))) +
geom_bar(position = "dodge", stat = "identity") +
theme() +
labs(fill = "Experiment") +
xlab('Time')+
ylab('Size (0 - 100)')
dev.off()
}
For example for trait 25 generate this file:
Experiment time trait value$Mean $N $SD $Min $Max $Coeff.Variation
0 5 Tenderness 56.2 20 17.9 6 81 31.9
0 15 Tenderness 68.2 20 22.6 9 100 33.1
0 25 Tenderness 61.2 20 21.7 12 97 35.4
1 5 Tenderness 61.3 72 25.0 0 100 40.8
1 15 Tenderness 65.3 72 21.2 5 100 32.4
1 25 Tenderness 72.6 72 22.8 8 100 31.4
But the saved graphics are blank, however, when I run the same code for the graphics outside from for{}
the code works perfectly. Some suggestion?
One solution is to store your plots in a list and then print()
them.
See a little example:
First: Let´s save our plots to a list
library(ggplot2)
list <- list()
for (i in 1:3) {
g <- ggplot(iris, aes(Sepal.Length,Sepal.Width)) +
geom_point()
list[[i]] <- g
}
We now have our list filled with plots. Now, let´s save them to tiff
.
for (i in 1:3) {
file_name = paste("iris_plot_", i, ".tiff", sep="")
tiff(file_name)
print(list[[i]])
dev.off()
}