有没有办法在ggplot中分离一个条形图,该条形图取前n行,然后生成一个条形图,然后再生成下n行,直到nrow(df)完成?
这是我的pesudo代码:有没有办法在ggplot中分离一个条形图,该条形图取前n行,然后生成一个条形图,然后再生成下n行,直到nrow(df)完成?,r,ggplot2,R,Ggplot2,这是我的pesudo代码: df <- data.frame("Percent" = sample.int(100,100), "Name" = str_c("John", sample.int(100,100))) x <- df p <- ggplot(x, aes(x=x$Name, y=x$Percent)) + geom_col()+ coord_flip() p df这里有一种方法,通过向数据帧添加分组列: # Create groups withi
df <- data.frame("Percent" = sample.int(100,100), "Name" = str_c("John", sample.int(100,100)))
x <- df
p <- ggplot(x, aes(x=x$Name, y=x$Percent)) +
geom_col()+
coord_flip()
p
df这里有一种方法,通过向数据帧添加分组列:
# Create groups within df of max size 20
max_per_plot = 20
n_groups = ceiling(nrow(df)/max_per_plot)
groups = rep(1:n_groups, each=max_per_plot)
df$group = groups[1:nrow(df)]
# Make a plot for each group
for (grp in 1:n_groups) {
p = ggplot(df %>% filter(group==grp), aes(Name, Percent)) +
geom_col() + coord_flip()
print(p) # Use print to force plot output within the loop
}
库(tidyverse)
#示例数据集
df%
mutate(id=row_number()%/%21)%>%#创建一个分组变量(每20行)
每个分组子数据集的组嵌套(id)%>%#
mutate(plt=map(data,~ggplot(.x,aes(Name,y=Percent))+#创建并保存绘图
geom_col()+
coord_flip()))
以下是您的新数据集(存储了绘图)的外观:
df_plots
# # A tibble: 5 x 3
# id data plt
# <dbl> <list> <list>
# 1 0 <tibble [20 × 2]> <gg>
# 2 1 <tibble [21 × 2]> <gg>
# 3 2 <tibble [21 × 2]> <gg>
# 4 3 <tibble [21 × 2]> <gg>
# 5 4 <tibble [17 × 2]> <gg>
df_图
##tibble:5 x 3
#id数据plt
#
# 1 0
# 2 1
# 3 2
# 4 3
# 5 4
您可以像下面这样从相应的列访问每个绘图df_plots$plt[[1]]
您可以像这样访问生成每个绘图的数据df_plots$data[[1]]
您是否考虑过使用facet_wrap()
将所有分割的绘图放在一起?您可以使用@Kent方法,然后使用+facet\u wrap(~group)
这正是我想要的,我甚至没有想到使用分组变量循环它。非常感谢。我喜欢tidyverse替代品。我会认真考虑这两个答案,非常感谢!!!
df_plots
# # A tibble: 5 x 3
# id data plt
# <dbl> <list> <list>
# 1 0 <tibble [20 × 2]> <gg>
# 2 1 <tibble [21 × 2]> <gg>
# 3 2 <tibble [21 × 2]> <gg>
# 4 3 <tibble [21 × 2]> <gg>
# 5 4 <tibble [17 × 2]> <gg>