5

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?

0

2 Answers 2

2

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")
Sign up to request clarification or add additional context in comments.

2 Comments

What if you want to mix string with non-string? One can use aes(get("STRING"), non-STRING), but what about aes_string("STRING", non-STRING)?
@PoGibas, I would strongly suggest avoiding non-standard evaluation in functions. If you really need to do this, use aes_. I'm not good at using it, because I've never found it necessary. Usually, adding columns inside the function and referring to them by name results in simpler code.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.