We are working with a survey data and I was making the frequency distribution graphs for each column. I have used the following code:
png(file="saving_plot.png")
barplot(freq$n_1, #(freq is my table of frequencias, and n1 the name of the first column)*
main="Frequency distribution N_1",
xlab="Degree of agreement",
ylab="Absolute frequency",
names.arg = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"),
col= "#69b3a2")
dev.off()
So, with this, I've been renaming the column name manually, pulling each chart out of a total of 120 columns, totally inefficient. How can I do this same thing, save an image of each bar chart for each column more efficiently?
Note: I will show you the first seven columns, since there are 140...
structure(list(Nu_1 = c(17L, 7L, 14L, 20L, 49L, 190L, 217L, 375L,
550L, 414L, 836L, 9L), Nu_2 = c(77L, 14L, 39L, 56L, 83L, 412L,
287L, 425L, 469L, 327L, 499L, 10L), Nu_3 = c(49L, 7L, 28L, 36L,
82L, 353L, 323L, 496L, 462L, 309L, 537L, 16L), Nu_4 = c(308L,
149L, 212L, 248L, 229L, 537L, 349L, 293L, 169L, 84L, 110L, 10L
), Nu_5 = c(64L, 24L, 42L, 53L, 90L, 273L, 257L, 407L, 463L,
308L, 710L, 7L), Nu_6 = c(366L, 121L, 226L, 273L, 236L, 548L,
282L, 230L, 180L, 84L, 142L, 10L)), class = "data.frame", row.names = c(NA,
-12L))
CodePudding user response:
You may loop over the names
of the data frame, e.g. using lapply
. Since this produces a lot of console output as well, you could wrap an invisible
around it.
dir.create('./plotdir') ## create an output directory in wd
invisible(
lapply(names(freq), \(x) {
png(file=sprintf("./plotdir/saving_plot_%s.png", x), 600, 400)
barplot(freq[[x]], main=paste("Frequency distribution", toupper(x)),
xlab="Degree of agreement",
ylab="Absolute frequency",
names.arg = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"),
col= "#69b3a2"
)
dev.off()
})
)