R pass variable column indices to ggplot2

RGgplot2Dataframe

R Problem Overview


I'm attempting to pass the column indices to ggplot as part of a function I'll be using repeatedly. like:

myplot <- function(df){
    ggplot(df, aes(df[, 1], df[, 2])) + geom_point()
}

I'll always be using the first column as my x variable and the second column as my y-variable, but the column names change between data sets. I've searched all over.. Any ideas?

EDIT:

This is the answer I used:

require(ggplot2)

myplot <- function(df){
   ggplot(df, aes_string(colnames(df)[1], colnames(df)[2])) + geom_point()
}

R Solutions


Solution 1 - R

You can use the aes_string in stead of aes to pass string in stead of using objects, i.e.:

myplot = function(df, x_string, y_string) {
   ggplot(df, aes_string(x = x_string, y = y_string)) + geom_point()
 }
myplot(df, "A", "B")
myplot(df, "B", "A")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionN8TROView Question on Stackoverflow
Solution 1 - RPaul HiemstraView Answer on Stackoverflow