我在R中运行一个有多次迭代的代码。每个结果都存储在一个名为accatable
的表中。如您所见,在下面的示例中,只有行S2*
> accatable
1 2 3 4 5 6 7
S1 NA NA NA NA NA NA NA
S2 NA NA NA NA NA NA NA
S1_S2 NA NA NA NA NA NA NA
S2* 0.737714 0.7083141 0.767515 0.8060774 0.7800401 0.8015116 0.815209
S1_S2* NA NA NA NA NA NA NA
我想要创建的是使用ggplot2
显示进化的图表。例如,您运行第一次迭代并获取行S2*
列1
的值。然后在第二次迭代中,您将获得行S2*
列2
等的值。
目标是在每次迭代后绘制一个图表,每次都会更新以显示进化。
到目前为止,我已设法创建该图表,但仅在所有表格完成时才创建。这是我试过的测试。我首先创建df
并将其从宽格式转换为长格式。然后我使用ggplot
来创建输出
testdf <- replicate(7, sample(0:10,5,rep=TRUE))
colnames(testdf) <- as.character(seq(1,7))
rownames(testdf) <- c("S1", "S2", "S1_S2", "S2*", "S1_S2*")
test <- melt(testdf, id.vars=testdf[[1]])
colnames(test) <- c("Input", "Images", "Acca")
test
test$IMAGES <- as.numeric(as.vector(test$Images))
ggplot (data = test, aes(x=Images, y=Acca, group=Input, colour=Input)) +
geom_line(aes(linetype=Input)) +
geom_point() +
scale_colour_manual(name="Scenario",
values = c("black","black","blue","blue","red","red",
"darkgreen","darkgreen")) +
scale_linetype_manual(name="Scenario",
values=c("solid","dashed","solid","dashed","solid", "dashed",
"solid","dashed","solid","dashed", "solid","dashed")) +
theme_minimal() +
labs(x="Images", y="Acca",title="test") +
theme(plot.title = element_text(hjust = 0.5)) +
scale_x_continuous("Images", c(1,2,3,4,5,6,7), c(1,2,3,4,5,6,7))
我知道如何在每次添加新值时调整ggplot
代码来绘制表格吗?
答案 0 :(得分:1)
这是一个tidyverse
解决方案。
为了说明这一点,我创建了一个与testdf
大小相同的空白数据框,以便迭代更新:
testdf <- as.data.frame(testdf)
accatable <- data.frame(`1` = rep(NA, 5), `2` = rep(NA, 5),
`3` = rep(NA, 5), `4` = rep(NA, 5),
`5` = rep(NA, 5), `6` = rep(NA, 5),
`7` = rep(NA, 5),
row.names = rownames(testdf))
> accatable
X1 X2 X3 X4 X5 X6 X7
S1 NA NA NA NA NA NA NA
S2 NA NA NA NA NA NA NA
S1_S2 NA NA NA NA NA NA NA
S2* NA NA NA NA NA NA NA
S1_S2* NA NA NA NA NA NA NA
假设在for循环中运行i
,数据框的i
列将更新:
library(dplyr)
p.list <- vector("list", ncol(accatable))
for(i in seq_along(accatable)){
accatable[, i] <- testdf[, i] # replace with your actual updating code
p <- ggplot(accatable[, seq(1, i), drop = FALSE] %>% # keep only first 1-i columns
tibble::rownames_to_column(var = "Scenario") %>% # add row name as a column
tidyr::gather(iteration, value, -Scenario), # convert to long format
aes(x = iteration, y = value, group = Scenario,
color = Scenario, linetype = Scenario)) +
geom_line() +
geom_point() +
labs(x = "Images", y = "ACCA", title = paste("Iteration:", i)) +
theme_minimal()
print(p) # if you just want to SEE the result from each iteration
p.list[[i]] <- ggplotGrob(p) # if you want to SAVE the result from each iteration
}
gridExtra::grid.arrange(grobs = p.list, ncol = 1)
结果如下所示:
(我已从示例代码中省略了scale_XX()
规范,因为我认为它们对解决方案不是必不可少的。您可以根据需要调整外观和感觉。)