r - 为数据框中变量的每个值重复一个 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
要在标题中使用的值。
谁能帮我解决这个问题?
解决方案
推荐阅读
- node.js - 在 NodeJs 和 Express 中跟踪 SocketID
- php - Link for CSS.php?
- java - 用户输入所有数据后检索数据时应用程序崩溃?
- v8 - 如何在 V8 javascript 引擎中启用和使用 ES6 模块?
- javascript - JavaScript while循环不适用于for循环
- pandas - 使用 Pandas 的属性的合并和计数
- c# - 就地改变”C#中ComboBox中的选定值
- c - C - 从 'void*' 到 'void (*)()' 的无效转换
- c++ - 指针行为将值设为 1
- python - 使用异步编程每秒打印按键