Best way to plot automatically all data.table columns using ggplot2

前端 未结 2 759
刺人心
刺人心 2021-01-07 14:08

I\'m trying to make use of advanced tricks from data.table and ggplot2 functionalities to create a simple yet powerful function that automatically

2条回答
  •  情深已故
    2021-01-07 14:35

    I hope this works for you:

    plotAllXYbyZ <- function(dt, x, y, z) {
      # to make sure all columns to be melted for ploting are numerical 
      dt[, (y):= lapply(.SD, function(x) {as.numeric(as.character(x))}), .SDcols = y]
      dts <- melt(dt, id = c(x,z), measure = y)
      ggplot(dts, aes_string(x = colnames(dt)[x], y = "value", colours = colnames(dt)[z])) +
        geom_line() + facet_wrap(~ variable)
    }
    
    dt <- data.table(mtcars)    
    
    plotAllXYbyZ(dt, x=1, y=3:10, z=2)
    

提交回复
热议问题