简体   繁体   English

如何为在 lapply 循环中创建的 ggplots 分配唯一的标题和文本标签?

[英]How to assign unique title and text labels to ggplots created in lapply loop?

I've tried about every iteration I can find on Stack Exchange of for loops and lapply loops to create ggplots and this code has worked well for me.我已经尝试了我可以在堆栈交换上找到的 for 循环和 lapply 循环的每一次迭代来创建 ggplots,这段代码对我来说效果很好。 My only problem is that I can't assign unique titles and labels.我唯一的问题是我无法分配唯一的标题和标签。 From what I can tell in the function i takes the values of my response variable so I can't index the title I want as the ith entry in a character string of titles.从我在函数中可以看出,我采用响应变量的值,因此我无法将我想要的标题作为标题字符串中的第 i 个条目进行索引。

The example I've supplied creates plots with the correct values but the 2nd and 3rd plots in the plot lists don't have the correct titles or labels.我提供的示例创建了具有正确值的绘图,但绘图列表中的第二个和第三个绘图没有正确的标题或标签。

Mock dataset:模拟数据集:

library(ggplot2)

nms=c("SampleA","SampleB","SampleC")
measr1=c(0.6,0.6,10)
measr2=c(0.6,10,0.8)
measr3=c(0.7,10,10)
qual1=c("U","U","")
qual2=c("U","","J")
qual3=c("J","","")
df=data.frame(nms,measr1,qual1,measr2,qual2,measr3,qual3,stringsAsFactors = FALSE)

identify columns in dataset that contain response variable识别数据集中包含响应变量的列

measrsindex=c(2,4,6)

Create list of plots that show all samples for each measurement创建显示每次测量的所有样本的图列表

plotlist=list()
plotlist=lapply(df[,measrsindex], function(i) ggplot(df,aes_string(x="nms",y=i))+
             geom_col()+
             ggtitle("measr1")+
             geom_text(aes(label=df$qual1)))

Create list of plots that show all measurements for each sample创建显示每个样本的所有测量值的图列表

plotlist2=list()
plotlist2=lapply(df[,measrsindex],function(i)ggplot(df,aes_string(x=measrsindex, y=i))+
              geom_col()+
              ggtitle("SampleA")+
              geom_text(aes(label=df$qual1)))

The problem is that I cant create unique title for each plot.问题是我无法为每个情节创建唯一的标题。 (All plots in the example have the title "measr1" or "SampleA) (示例中的所有图都具有标题“measr1”或“SampleA”)

Additionally I cant apply unique labels (from qual columns) for each bar.此外,我无法为每个条形应用唯一标签(来自 qual 列)。 (ex. the letter for qual 2 should appear on top of the column for measr2 for each sample) (例如,qual 2 的字母应出现在每个样本的 measr2 列的顶部)

Additionally in the second plot list the x-values aren't "measr1","measr2","measr3" they're the index values for those columns which isn't ideal.此外,在第二个绘图列表中,x 值不是“measr1”、“measr2”、“measr3”,它们是那些不理想的列的索引值。

I'm relatively new to R and have never posted on Stack Overflow before so any feedback about my problem or posting questions is welcomed.我对 R 比较陌生,之前从未在 Stack Overflow 上发过贴,因此欢迎任何有关我的问题或发布问题的反馈。

I've found lots of questions and answers about this sort of topic but none that have a data structure or desired plot quite like mine.我发现了很多关于这类主题的问题和答案,但没有一个像我的那样具有数据结构或所需的情节。 I apologize if this is a redundant question but I have tried to find the solution in previous answers and have been unable.如果这是一个多余的问题,我深表歉意,但我试图在以前的答案中找到解决方案,但一直未能找到。

This is where I got the original code to make my loops, however this example doesn't include titles or labels: Looping over ggplot2 with columns这是我获得原始代码来制作我的循环的地方,但是这个例子不包括标题或标签: 循环使用列的 ggplot2

You could loop over the names of the columns instead of the column itself and then use some non-standard evaluation to get column values from the names.您可以遍历列的名称而不是列本身,然后使用一些非标准评估从名称中获取列值。 Also, I have included label in aes .另外,我在aes包含了 label 。

library(ggplot2)
library(rlang)

plotlist3 <- purrr::map(names(df)[measrsindex], 
             ~ggplot(df, aes(nms, !!sym(.x), label = qual1)) + 
               geom_col() + ggtitle(.x) + geom_text(vjust = -1))

plotlist3[[1]]

在此处输入图片说明

plotlist3[[2]]

在此处输入图片说明


The same can be achieved with lapply as well lapply也可以实现同样的效果

plotlist4 <- lapply(names(df)[measrsindex], function(x)
  ggplot(df, aes(nms, !!sym(x), label = qual1)) + 
         geom_col() + ggtitle(x) + geom_text(vjust = -1))

I would recommend putting your data in long format prior to using ggplot2 , it makes plotting a much simpler task.我建议在使用ggplot2之前将您的数据放入长格式,它使绘图变得更加简单。 I also recoded some variables to facilitate constructing the plot.我还重新编码了一些变量以方便构建绘图。 Here is the code to construct the plots with lapply .这是使用lapply构造图的代码。

library(tidyverse)

#Change from wide to long format
df1<-df %>% 
  pivot_longer(cols = -nms,
               names_to = c(".value", "obs"),
               names_sep = c("r","l")) %>%
  #Separate Sample column into letters
  separate(col = nms,
           sep = "Sample",
           into = c("fill","Sample"))

#Change measures index to 1-3
measrsindex=c(1,2,3)

plotlist=list()
plotlist=lapply(measrsindex, function(i){
  #Subset by measrsindex (numbers) and plot
  df1 %>%
    filter(obs == i) %>%
    ggplot(aes_string(x="Sample", y="meas", label="qua"))+
    geom_col()+
    labs(x = "Sample") +
    ggtitle(paste("Measure",i, collapse = " "))+
    geom_text()})

#Get the letters A : C
samplesvec<-unique(df1$Sample)

plotlist2=list()
plotlist2=lapply(samplesvec, function(i){
  #Subset by samplesvec (letters) and plot
  df1 %>%
    filter(Sample == i) %>%
    ggplot(aes_string(x="obs", y = "meas",label="qua"))+ 
    geom_col()+
    labs(x = "Measure") +
    ggtitle(paste("Sample",i,collapse = ", "))+
    geom_text()})

Watching the final plots, I think it might be useful to use facet_wrap to make these plots.看着最后的图,我认为使用facet_wrap来制作这些图可能很有用。 I added the code to use it with your plots.我添加了代码以将其用于您的绘图。

#Plot for Measures
ggplot(df1, aes(x = Sample, 
                y = meas, 
                label = qua)) +
  geom_col()+
  facet_wrap(~ obs) +
  ggtitle("Measures")+
  labs(x="Samples")+
  geom_text()

#Plot for Samples
ggplot(df1, aes(x = obs, 
                y = meas, 
                label = qua)) +
  geom_col()+
  facet_wrap(~ Sample) +
  ggtitle("Samples")+
  labs(x="Measures")+
  geom_text()

Here is a sample of the plots using facet_wrap .这是使用facet_wrap的图facet_wrap

措施

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

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