我的数据中有几行是这样的:
我正在尝试在 R 中编写一个循环程序,它采用一组具有相似名称/值的行,并在循环中为存储在 R 中单列“Variable_name”中的具有相似名称/值的行生成条形图。
到目前为止,我尝试为每组行创建一个单独的数据表,按行值进行过滤,然后将其传递给 ggplot。
[可以工作,但不想经历这个过程]乏味/手动过程:
data[is.na(data)]<-'NA' #Turning NA as a valid value so that it get's included in the bar diagram.
bar_data1 <- data %>%
filter(Variable_name == 'Gender')
ggplot(bar_data1, aes(x=Levels, y=Count, fill=Levels))+geom_bar(stat="identity")+theme_minimal()+scale_y_continuous(breaks=c(0,10,20,50,100,150))
[想要但不起作用]我也尝试过这个for循环:
for(i in 1:2){
print(ggplot(data, aes(x=Levels, y=Count, fill=Levels))+geom_bar(stat="identity")+theme_minimal()+scale_y_continuous(breaks=c(0,10,20,50,100,150)))
}
我编写的循环程序的问题是它会永远运行,最终 R 停止响应。内存不足了吗?我认为我的循环程序有问题。
关于如何使其通过循环程序工作有什么建议吗?
最佳答案
这是 mtcars 的示例。我们将根据汽车的 cyl
数量绘制 3 个直方图,分为 3 组:
我们将使用 purrr::map()
函数代替 for 循环:
library(tidyverse)
groups <- names(table(mtcars$cyl))
plots <- map(groups,
function(group) {
(
mtcars
%>% filter(cyl == group)
%>% ggplot(aes(hp))
+ geom_histogram()
)})
print(plots)
但是如果您想在同一个图形上绘制所有直方图,请使用facet_wrap()
:
(
mtcars
%>% ggplot(aes(hp))
+ geom_histogram()
+ facet_wrap(~cyl)
)
关于r - 如何循环创建多个条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67026497/