使用链接命令在循环中打印 ggplot
print ggplot in a loop using chaining command
我正在尝试循环制作一组 ggplots 并显示它们。我正在尝试使用 %>%
运算符。这是绘制从 1 到 10 的点的玩具示例,每个点都有不同的标题。
library(magrittr)
library(ggplot2)
data1 <- data.frame('x' = 1:10, 'y' = 1:10)
for (index in 1:10){
data1 %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index)))
}
现在,以下代码可以工作并生成 10 个图,每个图都有不同的标题
library(magrittr)
library(ggplot2)
data1 <- data.frame('x' = 1:10, 'y' = 1:10)
for (index in 1:10){
print(ggplot(data = data1, aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index))))
}
但是,我想使用 %>%
运算符生成一系列图。我在标题末尾尝试了 %>% print()
,它运行但不生成显示图。而
for (index in 1:10){
data1 %>%
print(data = .,ggplot(aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index))))
}
产生错误
Error: ggplot2 doesn't know how to deal with data of class uneval
有没有我遗漏的愚蠢的东西?
谢谢!
%>%
和+
之间确实是运算顺序的问题。您可以像
这样一起屏蔽 ggplot
内容
for (index in 1:10){
data1 %>% {
ggplot(., aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index)))
} %>% print
}
或者您可以将整个链条放在打印件中
for (index in 1:10) {
print(data1 %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index)))
)
}
我正在尝试循环制作一组 ggplots 并显示它们。我正在尝试使用 %>%
运算符。这是绘制从 1 到 10 的点的玩具示例,每个点都有不同的标题。
library(magrittr)
library(ggplot2)
data1 <- data.frame('x' = 1:10, 'y' = 1:10)
for (index in 1:10){
data1 %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index)))
}
现在,以下代码可以工作并生成 10 个图,每个图都有不同的标题
library(magrittr)
library(ggplot2)
data1 <- data.frame('x' = 1:10, 'y' = 1:10)
for (index in 1:10){
print(ggplot(data = data1, aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index))))
}
但是,我想使用 %>%
运算符生成一系列图。我在标题末尾尝试了 %>% print()
,它运行但不生成显示图。而
for (index in 1:10){
data1 %>%
print(data = .,ggplot(aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index))))
}
产生错误
Error: ggplot2 doesn't know how to deal with data of class uneval
有没有我遗漏的愚蠢的东西?
谢谢!
%>%
和+
之间确实是运算顺序的问题。您可以像
ggplot
内容
for (index in 1:10){
data1 %>% {
ggplot(., aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index)))
} %>% print
}
或者您可以将整个链条放在打印件中
for (index in 1:10) {
print(data1 %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
ggtitle(paste("plot ",as.character(index)))
)
}