我创建了一个函数,读取 csv 文件,将数据处理到数据框中,在 (2,1) 布局中制作箱线图和条形图,然后保存在 png 文件中。如果我运行一个函数,它确实会显示正确的数据框,但绘图不会保存。如果我独立运行绘图代码,Rstudio 会正确显示绘图。请帮忙...
data <- read.csv("file name here", stringsAsFactors = FALSE)
F4 <- function(data) {
data <- data[, !colnames(data) %in% "blank"]
names(data) <- c("district", "confirmed", "deceased", "recovered")
data[,"active"] <- data$confirmed - data$recovered - data$deceased
data <- data[, c("district", "active", "confirmed", "recovered", "deceased")]
data <- data[1:30, ]
return(data)
png("png file name here", width=100, height=500)
par(mfrow = c(2, 1), mar = c(4, 4, 4, 4), oma = c(0, 0, 0, 0))
boxplot(data$active, data$confirmed, data$recovered, data$deceased, col = "skyblue", ylab = "No. of Cases",
main = "Boxplot of COVID-19 status")
axis(1, at = 1, labels = "Active")
axis(1, at = 2, labels = "Confirmed")
axis(1, at = 3, labels = "Recovered")
axis(1, at = 4, labels = "Deceased")
barplot(data$confirmed, col = "skyblue", ylim = c(0, 200), names.arg = 1:30,
xlab = "District", ylab = "No. of Cases", main = "COVID-19 status by region")
barplot(data$recovered, col = "yellowgreen", add = TRUE)
barplot(data$deceased, col = "tomato", add = TRUE)
legend("topright", legend = c("Confirmed", "Recovered", "Deceased"), fill=c("skyblue", "yellowgreen", "tomato"), horiz=TRUE, cex = 0.9)
dev.off()
}
如果我独立运行绘图代码,Rstudio 会正确显示绘图。请帮忙...
F4 <- function(data) {
data <- data[, !colnames(data) %in% "blank"]
names(data) <- c("district", "confirmed", "deceased", "recovered")
data[, "active"] <- data$confirmed - data$recovered - data$deceased
data <- data[, c("district", "active", "confirmed", "recovered", "deceased")]
data <- data[1:30, ]
png("foo.png", 800, 1000)
par(mfrow=c(2, 1), mar=c(4, 4, 4, 4), oma=c(0, 0, 0, 0))
boxplot(data$active, data$confirmed, data$recovered, data$deceased,
col="skyblue", ylab="No. of Cases",
main="Boxplot of COVID-19 status")
axis(1, at=1, labels="Active")
axis(1, at=2, labels="Confirmed")
axis(1, at=3, labels="Recovered")
axis(1, at=4, labels="Deceased")
barplot(data$confirmed, col="skyblue", ylim=c(0, 200), names.arg=1:30,
xlab="District", ylab="No. of Cases",
main="COVID-19 status by region")
barplot(data$recovered, col="yellowgreen", add=TRUE)
barplot(data$deceased, col="tomato", add=TRUE)
legend("topright", legend=c("Confirmed", "Recovered", "Deceased"),
fill=c("skyblue", "yellowgreen", "tomato"), horiz=TRUE, cex=0.9)
dev.off()
return(data)
}