1

Is there a simpler way in ggplot to plot columns by their indices, as in function below?

plotYofX <- function(dt,x,y) {
    dt[,  lapply(.SD, function(x) {as.numeric(x)}), .SDcols = c(x,y)]
    ggplot(dt) + geom_step(aes(x=get(names(dt)[x]), y=get(names(dt)[y]))) + labs(x=names(dt)[x], y=names(dt)[y]) 

Typing every time get(names(dt)[x] and then also correcting axis names using labs (e.g. instead of just writing aes(x,y)) seems quite convoluted for such a smart package as ggplot2...

This ggplot example is taken from discussion here: Don't want original data.table to be modified when passed to a function.

IVIM
  • 2,167
  • 1
  • 15
  • 41
  • 2
    As far as I can tell you want `aes_string()` which allows you to pass strings to `aes()` instead of unquoted column names. If `x` and `y` are indices, it'd be something like `ggplot(aes_string(colnames(df)[x], colnames(df)[y]))` – Marius Jun 21 '17 at 02:30

1 Answers1

1

Thanks to Marius comment above:

One needs to use aes_string() which allows you to pass strings to aes() instead of unquoted column names. If x and y are indices, it'd be something like ggplot(aes_string(colnames(df)[x], colnames(df)[y]))

IVIM
  • 2,167
  • 1
  • 15
  • 41