1

This question is based on attempts I made following finding this question: Making plot functions with ggplot and aes_string

Example data:

df<-data.frame(a=1:12,b=1:12)

So I have the following code, which is not in a function but looks exactly how I want:

dff <- df
x.var <- "a"
y.var <- "b"
xlabel <- "a axis" 
ylabel <- "b axis"

ymax <- max(dff[,y.var])
datalabels <- dff[,y.var]
print(ggplot(dff, aes_string(x = x.var, y = y.var)) + 
        geom_bar(stat = "identity")+
        geom_text(aes(label=datalabels)) +
        xlab(xlabel) + ylab(ylabel)  
)

But i'd really like it to be functionalised (my actual code has a bunch of other formatting things and it would be much easier for repetitive graphs if I could just call a function).

I tried this, which doesn't recognise the labels:

plot.fun.one <- function(dff, x.var, y.var, xlabel, ylabel){
  ymax <- max(dff[,y.var])
  datalabels <- dff[,y.var]

  print(ggplot(dff, aes_string(x = x.var, y = y.var)) + 
          geom_bar(stat = "identity")+
          geom_text(aes(label=datalabels)) +
          xlab(xlabel) + ylab(ylabel)  
  )
}

plot.fun.one(df, 
             x.var = 'a', 
             y.var = 'b', 
             xlabel = "a axis", 
             ylabel = "b axis")

Then I found this answer: Format geom_text label doesn't work when using aes_string, so I tried the following, which sort of works, but labels everything "1", which is wrong:

plot.fun.one <- function(dff, x.var, y.var, xlabel, ylabel){
  ymax <- max(dff[,y.var])
  datalabels <- dff[,y.var]

  print(ggplot(dff, aes_string(x = x.var, y = y.var)) + 
          geom_bar(stat = "identity")+
          geom_text(data = dff, aes_string(x = x.var, y = y.var, label=datalabels)) +
          xlab(xlabel) + ylab(ylabel)  
  )
}

plot.fun.one(df, 
             x.var = 'a', 
             y.var = 'b', 
             xlabel = "a axis", 
             ylabel = "b axis")

I am certain I'm missing something really obvious but I am blind to it at the moment, and any help would be greatly appreciated!

Community
  • 1
  • 1
Froom2
  • 1,159
  • 2
  • 10
  • 23
  • On my computer (ggplot 0.9.3.1, R 3.1.2) your first plot (i.e. what you want) and the output from the first `plot.fun.one` above seem identical. What's the problem? – Ben B-L Dec 01 '14 at 16:30
  • if you add `datalabels – rawr Dec 01 '14 at 16:31

0 Answers0