user7353167
user7353167

Reputation:

ggplot2 pass variable to plot to a function

I use ggplot to use multiple plots, so I built my own function.

plothist <- function(a) {
  ggplot(aes(x = a), data = data) + geom_histogram()
}

p1 <- plothist(data$fixed.acidity)
p2 <- plothist(data$volatile.acidity)
p3 <- plothist(data$citric.acid)
p4 <- plothist(data$residual.sugar)
p5 <- plothist(data$chlorides)
p6 <- plothist(data$free.sulfur.dioxide)
p7 <- plothist(data$total.sulfur.dioxide)
p8 <- plothist(data$density)
p9 <- plothist(data$pH)
p10 <- plothist(data$sulphates)
p11 <- plothist(data$alcohol)

x <- grid.arrange(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11,
                  top = "Histogram of independent variables")
x

the x-axis does not have the name of the variable, I only can see "a" on every plot, which makes the plots pretty useless. Can you help me how to display the actual variable there?

Upvotes: 5

Views: 2020

Answers (2)

Nathan Werth
Nathan Werth

Reputation: 5263

Use aes_string for this kind of programming:

library(ggplot2)

plothist <- function(data, column) {
  ggplot(data, aes_string(x = column)) + geom_histogram()
}

plothist(data, "fixed.acidity")

Upvotes: 2

pogibas
pogibas

Reputation: 28309

Your function needs only minor edits:

plotHist <- function(inputData, columnToPlot) {
    # Load library as your function doesn't know
    # what is this ggplot function you want to use
    library(ggplot2)
    resultPlot <- ggplot(inputData, aes(get(columnToPlot))) + 
        geom_histogram() +
        labs(x = columnToPlot)
    return(resultPlot)
}
plotHist(mtcars, "cyl")

columnToPlot is name of a column you want to plot. Also you need to pass inputData argument as your given function doesn't know what dinputData is.

Upvotes: 2

Related Questions