简体   繁体   English

使用 lapply 创建带有 x 标签的 ggplot2 直方图

[英]using lapply to create ggplot2 histograms with x labels

I am trying to use lapply to generate xlab histogram titles for each histogram in the function我正在尝试使用 lapply 为 function 中的每个直方图生成 xlab 直方图标题

plot.labels <- colnames(total_data[27:50])

out1 = lapply(total_data[,27:50], function(x){ggplot(data.frame(x), aes(x, fill=total_data$status,color=total_data$status)) + geom_histogram() + labs(x=plot.labels[x])})

View(plot.labels)

plot labels look normal, ex: 1 "pct_Myristic" "pct_Palmitic" "pct_Palmitelaidic" plot 标签看起来正常,例如: 1 “pct_Myristic”“pct_Palmitic”“pct_Palmitelaidic”

I have seen previous answers Histograms using ggplot2 within loop and Using lapply to pass labels to ggplot2 which were helpful for me to create the intial code, and the lapply loop works well to generate all the bivariate histograms w/ ggplot2 since i can't use hist() to seperate the two groups but applying the xlab is giving me trouble. I have seen previous answers Histograms using ggplot2 within loop and Using lapply to pass labels to ggplot2 which were helpful for me to create the intial code, and the lapply loop works well to generate all the bivariate histograms w/ ggplot2 since i can't use hist() 将两组分开,但应用 xlab 给我带来了麻烦。 seems that the plot.labels[x] works for some but not all graphs似乎 plot.labels[x] 适用于某些但并非所有图表

looks like this, some xlabs are missing histograms看起来像这样,一些 xlabs 缺少直方图

To expand on my comment about avoiding the loop, and using mtcars as OP hasn't provided their input data...为了扩展我关于避免循环的评论,并使用mtcars作为 OP 没有提供他们的输入数据......

Create a long version of the dataset.创建数据集的长版本。

library(tidyverse)

longData <- mtcars %>% 
              pivot_longer(
                cols=c(mpg, cyl,  disp,  hp, drat,    wt,  qsec, vs, am, gear),
                names_to="Variable",
                values_to="Value"
              )

Now create the plots.现在创建图。

longData %>% 
  ggplot() +
    geom_histogram(aes(x=Value, fill=as.factor(carb)), position="identity") +
    facet_wrap(~Variable)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM