【发布时间】:2021-05-16 09:59:08
【问题描述】:
我想为我的数据框中的每个变量值制作一个图表,然后将该值作为标题传递给图表。我认为最好的方法是使用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 的值以在标题中使用。
谁能帮我解决这个问题?
【问题讨论】: