ggplot2 收集通用值

ggplot2 gather with generic values

我正在研究这个 df

Col0 <- c("AA", "BB", "CC", "DD","EE","FF")
    Col1 <- c(2,2,2,6,1,1)
    Col2 <- c(2,2,2,1,3,4)
    Col3 <- c(2,2,3,4,6,6)
    Col4 <- c(2,2,3,1,2,1)
    Col5 <- c(2,1,1,1,1,4)
    Col6 <- c(2,4,2,5,4,4)
    Col7 <- c(2,4,2,5,4,4)
    Col8 <- c(2,2,3,4,5,4)
    Col9 <- c(1,3,3,2,2,2)
    df<-data.frame(Col0,Col1,Col2,Col3,Col4,Col5,Col6,Col7,Col8,Col9)

我使用 facet 创建了一个图表

library(ggplot2)
library(tidyr)

pl<-df %>%
  gather(Hi, Val, -Col0) %>%
  ggplot(aes(Hi, Val, group = Col0, col = Col0)) + facet_grid(Col0 ~ .)

pl<- pl + geom_line() +theme(
  axis.text.x = element_text(angle = 90, hjust = 1))+ theme( panel.border = element_rect(colour = "black", fill=NA, size=1),legend.direction ="vertical",legend.position = "right")+guides(fill=guide_legend(ncol=1))+scale_y_continuous(labels=comma) +theme(legend.text = element_text(size=6))  

print(pl)

这个问题是可能的,而不是使用 Col0 将值传递给函数:

value<- names(df[1])

因为我正在研究很多 df,我想概括这个函数

要在函数中使用字符串,您将需要 ggplot2 和 tidyr 函数的标准评估版本。在 tidyr 中,这些以下划线结尾。在 ggplot2 中,您需要 aes_string(或者可能 aes_)。

tidyr 的标准评估部分看起来像这样:

df %>% gather_("Hi", "Val", select_vars_(names(.), 
                                         names(.), 
                                         exclude = "Col0"))

gather_ 中的所有内容都是字符串。使用 select_vars_ 的代码的复杂部分是因为您要排除这些列。参见 here

对于绘图,您只需将 aes 更改为 aes_string 并使用字符串作为变量名称。比较棘手的部分是如何在 facet_grid 中使用字符串,这可以使用 formula 来完成,如图 here.

该部分代码的更改如下所示:

ggplot(aes_string("Hi", "Val", group = "Col0", col = "Col0")) + 
    facet_grid(as.formula(paste("Col0", "~.")))

剩下的就是将其放入一个函数中。

plotfun = function(data, column) {
    data %>%
        gather_("Hi", "Val", select_vars_(names(.), 
                                          names(.), 
                                          exclude = column)) %>%
        ggplot(aes_string("Hi", "Val", group = column, col = column)) + 
        facet_grid(as.formula(paste(column, "~."))) + 
        geom_line() +
        theme(axis.text.x = element_text(angle = 90, hjust = 1),
              panel.border = element_rect(colour = "black", fill=NA, size=1),
              legend.direction ="vertical",
              legend.position = "right",
              legend.text = element_text(size=6)) + 
        guides(fill=guide_legend(ncol=1)) +
        scale_y_continuous(labels=comma)
}

plotfun(df, "Col0")