0

I am trying to get histograms of all columns of a data frame isNumVal using sapply. Codes below:

sapply(isNumVal, plotHist)

plotHist <- function(df){
          df <- tbl_df(df)

            print(
              ggplot(df, aes(x = df[1])) + geom_histogram() 
            )

          }

ggplot histograms

The x axis label in all the plots is showing df1.

How do i get it show the name of the columns?

  • Hi useR. its not working. ggplot is substituting "value" in place of "df[,1] in all plots with your code. – Ravi Shankar Hela Jun 18 '18 at 13:53
  • Because `df[1]` is what you assigned to x, not whatever the column is called – camille Jun 18 '18 at 13:54
  • It's also well documented that using the name of the data frame inside `aes` will often introduce errors and scoping issues. You can use a tidyeval approach, or there are other SO questions that will help programmatically create ggplots – camille Jun 18 '18 at 13:56
  • Possible duplicate of [using an apply function with ggplot2 to create bar plots for more than one variable in a data.frame](https://stackoverflow.com/questions/41895513/using-an-apply-function-with-ggplot2-to-create-bar-plots-for-more-than-one-varia) – camille Jun 18 '18 at 14:03
  • Add `+ xlab(lab name )` after your `geom_histogram( )` call as in http://ggplot2.tidyverse.org/reference/labs.html. Also see the example to properly write the `(aes())` function as pointed out by @camille – Andrew Jun 18 '18 at 14:20

1 Answers1

0

There are many other ways, here is one. Try to pass dataframe and the column name to your function, and use aes_string:

plotHist <- function(myDf, myCol){
  ggplot(myDf, aes_string(x = myCol)) + geom_histogram()
}

lapply(colnames(isNumVal), function(i) plotHist(isNumVal, i))
zx8754
  • 52,746
  • 12
  • 114
  • 209