对数据框中变量的每个值重复绘制 ggplot

问题描述 投票:0回答:3

我想为数据框中变量的每个值制作一个图表,然后将该值作为标题传递给图表。我认为最好的方法是使用apply()

系列函数,但我有点新手,不知道如何做到这一点。

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

df <- data.frame(furniture = 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(furniture, count)) + labs(title = 'value of {{type}} being plotted') df %>% filter(type=='bbb') %>% ggplot() + geom_col(aes(furniture, count)) + labs(title = 'value of {{type}} being plotted') df %>% filter(type=='ccc') %>% ggplot() + geom_col(aes(furniture, count)) + labs(title = 'value of {{type}} being plotted')
但这很快就会变成大量代码,具有足够的

type

级别,并假设每个图都有相当数量的附加代码。我们还假设我不想使用 
facet_wrap(~type)
。正如您所看到的,x 变量的值在不同类型的值之间变化很大,因此 
facet_wrap()
 会导致 x 轴上大量缺失空格。理想情况下,我只是创建一个函数,将 x 和 y 变量以及 
type
 作为输入,然后对 
type
 进行过滤,绘制图表,并提取 
type
 的值以在标题中使用。

有人可以帮我解决这个问题吗?

r ggplot2 dplyr apply
3个回答
2
投票
或者您可以创建自定义函数,然后

lapply

 覆盖 
type
 的级别

myplot <- function(var){ df %>% filter(type==var) %>% ggplot() + geom_col(aes(month, count)) + labs(title = paste0("value of ",var)) } plot.list <- lapply(unique(df$type), myplot) plot.list[[1]] plot.list[[2]] plot.list[[3]]

编辑

包含 x 变量作为参数::

myplot <- function(var, xvar) { df %>% filter(type == var) %>% ggplot() + geom_col(aes(x={{xvar}}, count)) + labs(title = paste0("value of ", var)) } plot.list <- lapply(unique(df$type), myplot,xvar=cutlery)
您错过了 

{{}}

(又名“curly curly”)运算符,它取代了用 
enquo
 引用并用 
!!
(又名“bang-bang”)取消引用的方法,并且必须传递参数 
xvar
作为 
lapply
 的额外参数,而不是 
lapply
 内部函数的额外参数
    


1
投票
您可以拆分

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]]

 返回 -


1
投票
从你的陈述“理想情况下,我只是创建一个函数,将 x 和 y 变量作为输入,然后输入...”我假设你特别想要一个将

x

y
 作为不同值的函数变量(例如向量)作为输入,而不是将整个 
dataframe
 作为输入。在这种情况下,这个功能可能会满足您的需求:

library(ggplot2) library(dplyr) myPlot_function = function(x, y, type) { gg_list = list() # empty list df = data.frame(x, y, type) type_n = length(unique(df$type)) # number of each type for (i in 1:type_n){ # loop over each type g = df %>% filter(type == type[i]) %>% ggplot() + geom_col(aes(x, y)) + labs(title = paste0("Value of ", type[i], " being plotted")) gg_list[[paste0("plot_", i)]] = g } return(gg_list) }
然后,您可以将 

x

y
type
 指定为向量。例如:

some_plots = myPlot_function(x = df$month, y = df$count, type = df$type)
函数 

myPlot_function

 返回包含您的绘图的 
list
。您现在可以使用 
some_plots$plot_1
some_plots[[1]]
 来查看您的绘图。例如:

some_plots$plot_1

© www.soinside.com 2019 - 2024. All rights reserved.