首页 > 解决方案 > 为数据框中变量的每个值重复一个 ggplot

问题描述

我想为我的数据框中的每个变量值制作一个图表,然后将该值作为标题传递给图表。我认为最好的方法是使用apply()函数系列,但我有点新手,不知道如何做到这一点。

例如,假设我有这个数据框:

df <- data.frame(month=c("Chair", "Table", "Rug", "Wardrobe", "Chair", "Desk", "Lamp", "Shelves", "Curtains", "Bed"),
                 cutlery=c("Fork", "Knife", "Spatula", "Spoon", "Corkscrew", "Fork", "Tongs", "Chopsticks", "Spoon", "Knife"),
                 type=c("bbb", "ccc", "aaa", "bbb", "ccc", "aaa", "bbb", "ccc", "aaa", "bbb"),
                 count=c(341, 527, 2674, 811, 1045, 4417, 1178, 1192, 4793, 916))

我可以手动浏览并选择type这样做的价值:

df %>% 
  filter(type=='aaa') %>% 
  ggplot() +
  geom_col(aes(month, count)) +
  labs(title = 'value of {{type}} being plotted')

df %>% 
  filter(type=='bbb') %>% 
  ggplot() +
  geom_col(aes(month, count)) +
  labs(title = 'value of {{type}} being plotted')

df %>% 
  filter(type=='ccc') %>% 
  ggplot() +
  geom_col(aes(month, count)) +
  labs(title = 'value of {{type}} being plotted')

但这很快就变成了很多代码,有足够的级别type并且假设每个情节都有相当数量的附加代码。我们还假设我不想使用facet_wrap(~type). 如您所见,x 变量的值在不同类型的值之间变化很大,因此facet_wrap()会导致沿 x 轴有很多缺失的空格。理想情况下,我只需创建一个函数,将 x 和 y 变量作为输入,type然后过滤type,制作绘图,并提取type要在标题中使用的值。

谁能帮我解决这个问题?

标签: rggplot2dplyrapply

解决方案


您可以拆分每个值的数据type并生成绘图列表。

library(tidyverse)

df %>%
  group_split(type) %>%
  map(~ggplot(.x) +
        geom_col(aes(month, count)) +
        labs(title = sprintf('value of %s being plotted', 
                              first(.x$type)))) -> plot_list

plot_list[[1]]返回:

在此处输入图像描述

plot_list[[2]]返回 -

在此处输入图像描述


推荐阅读