这是我的伪代码:
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
它创建的输出是一个条形图,列出了该条形图上的所有100个值。
我希望获取前20个,创建一个绘图,然后获取接下来的20个,以创建一个新绘图,直到数据的第n行为止。我想创建它,以便如果数据集之间的行数改变,我仍然可以创建一个报告,该报告在每个图形上都有〜20条,以提高可读性。
我在有关ggplot或geom_col()的文档中找不到|有关此特定情况的geom_barplot()。我是否只需要事先分解数据集?我可以创建多个数据帧,但是我最终还是不愿意这样做,因为这会弄乱我的环境?
这里是一种方法,可以在数据框中添加一个分组列:
# 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
}
library(tidyverse)
# example dataset
df <- data.frame(Percent = sample.int(100,100), Name = str_c("John", sample.int(100,100)))
df_plots = df %>%
mutate(id = row_number() %/% 21) %>% # create a grouping variable (per 20 rows)
group_nest(id) %>% # for each grouped sub-dataset
mutate(plt = map(data, ~ggplot(.x, aes(Name, y=Percent)) + # create and save the plot
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_plots$plt[[1]]