Reputation: 3343
I have written a function to get the Proportional Stacked Bar plot using ggplot
function. Right now I am using Column name in this ID
.
PropBarPlot<-function(df, mytitle=""){
melteddf<-melt(df, id="ID", na.rm=T)
ggplot(melteddf, aes(ID, value, fill=variable)) +
geom_bar(position="fill") +
theme(axis.text.x = element_text(angle=90, vjust=1)) +
labs(title=mytitle)
}
I want to make it generic. So I want to make use of column index instead of column name. I tried doing something like this.
PropBarPlot<-function(df, mytitle=""){
melteddf<-melt(df, id=names(df)[1], na.rm=T)
ggplot(melteddf, aes(names(df)[1], value, fill=variable)) +
geom_bar(position="fill") +
theme(axis.text.x = element_text(angle=90, vjust=1)) +
labs(title=mytitle)
}
But of no use. Can someone suggest me how to do this??
Thanks.
Upvotes: 16
Views: 13000
Reputation: 276
As pointed out by @Bryan Shalloway, the aes_string()
approach is now soft deprecated, and replaced by tidy evaluation. Using the tidy evaluation approach, my solution would be:
library(reshape)
library(ggplot2)
# let's start by creating an example dataframe
id <- c(1, 2, 3, 4)
var1 <- c(10, 20, 10, 20)
var2 <- c(6, 3, 2, 5)
df <- data.frame(id, var1, var2)
# Now let's build the function
PropBarPlot<-function(df, mytitle=""){
# here I create a variable that contains the first element of the vector
# of df column names (it's a string)
my_name <- colnames(df)[1]
# here we melt, using the new variable as the id parameter
melteddf<-melt(df, id=my_name, na.rm=T)
# and here we plot, using the .data pronoun and the new variable
ggplot(melteddf, aes(x = .data[[my_name]],y = value, fill = variable)) +
geom_bar(position="fill", stat="identity") +
theme(axis.text.x = element_text(angle=90, vjust=1)) +
labs(title=mytitle)
}
If you would like to learn more about tidy evaluation (with step-by-step explanation and practical examples), I wholeheartedly recommend the learnr tutorial by Ian Lyttle, available at https://ijlyttle.shinyapps.io/tidyeval/
Upvotes: 3
Reputation: 98449
As pointed out by @baptiste you should use aes_string()
instead of aes()
to use strings in defining x and y values. Also you should put value
and variable
inside quotes.
PropBarPlot<-function(df, mytitle=""){
melteddf<-melt(df, id=names(df)[1], na.rm=T)
ggplot(melteddf, aes_string(x=names(df)[1],y= "value", fill="variable")) +
geom_bar(position="fill") +
theme(axis.text.x = element_text(angle=90, vjust=1)) +
labs(title=mytitle)
}
Upvotes: 14