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!