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.
By using the R base df[] notation or select() function from dplyr package you can select a single column or select multiple columns by index position (column number) from the R Data Frame.
Use DataFrame. loc[] and DataFrame. iloc[] to select a single column or multiple columns from pandas DataFrame by column names/label or index position respectively. where loc[] is used with column labels/names and iloc[] is used with column index/position.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With