Reputation: 1809
I have a dply statement which outputs a ggplot. Here's the basic idea:
my_data %>%
group_by(group1) %>%
summarise(n = n()) %>%
ggplot(aes(x=reorder(group1, n), y=n)) +
#geom_segment(aes(xend = reorder(group1, n), y = 0 , yend = n), lineend = "round", size = 10, color="#E48312") +
geom_bar(stat = "identity", fill = "#E48312")
However, I want to display the ggplots in a grid. So when I try:
grid.arrange(my_data,
my_data,
ncol=2)
I get:
Error: Input must be a vector, not a `viewport` object. Run `rlang::last_error()` to see where the error occurred.
How can I save the ggplot as a plot within the dplyr statement?
Upvotes: 2
Views: 497
Reputation: 887108
We need to assign to a new object
out <- my_data %>%
group_by(group1) %>%
summarise(n = n()) %>%
ggplot(aes(x=reorder(group1, n), y=n)) +
#geom_segment(aes(xend = reorder(group1, n), y = 0 , yend = n),
# lineend = "round", size = 10, color="#E48312") +
geom_bar(stat = "identity", fill = "#E48312")
grid.arrange(out, out, ncol=2)
Upvotes: 1
Reputation: 766
Am I misunderstanding, or can you just assign each plot a name in the environment like this?
plot_1 <- my_data %>%
group_by(group1) %>%
summarise(n = n()) %>%
ggplot(aes(x=reorder(group1, n), y=n)) +
#geom_segment(aes(xend = reorder(group1, n), y = 0 , yend = n), lineend = "round", size = 10, color="#E48312") +
geom_bar(stat = "identity", fill = "#E48312")
plot_2 <- my_data %>%
group_by(group1) %>%
summarise(n = n()) %>%
ggplot(aes(x=reorder(group1, n), y=n)) +
#geom_segment(aes(xend = reorder(group1, n), y = 0 , yend = n), lineend = "round", size = 10, color="#E48312") +
geom_bar(stat = "identity", fill = "#E48312")
grid.arrange(plot_1,
plot_2,
ncol=2)
Upvotes: 1