1

I have been trying to figure this out for a while now and I have also searched a lot on the internet, but I could not find a solution to this problem.

I have the following code which works, but I can't get the column names to appear as titles in the plot:

    lapply(bank, function(a) {
    if (is.factor(a)){
    ggplot(bank, aes(x=a)) + geom_bar(aes(fill = bank$y), position = "fill") + geom_hline(yintercept = 0.1127) + geom_bar(aes(y = (..count..)/sum(..count..), alpha = 0.3), show.legend = FALSE)
    }
    else {
    ggplot(bank, aes(x = a)) + geom_histogram(aes(fill = bank$y), position = "fill") + geom_hline(yintercept = 0.1127) + geom_density(aes(y = ..scaled..))
    }
    })

I tried putting "a" in ggtitle and a bunch of other stuff but nothing worked. I would be greatful for any help!

Edit: I tried using this code now (looping through the names and using aes_string):

    lapply(names(bank), function(a) {
    if (is.factor(bank[[a]])){
    ggplot(bank, aes_string(x = a)) + geom_bar(aes(fill = bank$y), position = "fill") + geom_hline(yintercept = 0.1127) + geom_bar(aes(y = (..count..)/sum(..count..), alpha = 0.3), show.legend = FALSE)
    }
    else {
    ggplot(bank, aes_string(x = a)) + geom_histogram(aes(fill = bank$y),  position = "fill") + geom_hline(yintercept = 0.1127) + geom_density(aes(y = ..scaled..))
    }
    })

this code works, the error message was because of whitespace in the variable name

  • 1
    What exactly is in your `bank` object? Please make sure your problem is [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data so we can run it and test it. – MrFlick Jul 05 '17 at 21:05
  • actually it is the bank dataset from UCI machine learning repository – Mark Lakshman Jul 05 '17 at 21:10
  • Try switching to looping through the *names* of the dataset rather than the dataset. It will take a few tweaks of your function, including the use of `aes_string` and code like `is.factor(bank[[a]])`, but it will allow you to use your function argument directly within `ggtitle`. – aosmith Jul 05 '17 at 21:15
  • @aosmith I tried that, but i get this error now: Fehler in parse(text = x) : :1:5: unexpected symbol 1: has credit – Mark Lakshman Jul 05 '17 at 21:48
  • 1
    Post `dput(head(bank))` so that people can see what your data looks like. Also post an image of what you're currently getting, and then what you're trying to get. Using `ggtitle()` should work, and does with my test code, but without a working example it's hard to know what you're trying to achieve. – Eric Watt Jul 05 '17 at 21:49

0 Answers0