I am trying to build a function to use loops with ggplot2. The following code works fine and I can get a bar chart for each variable of the data frame:
library(ggplot2)
DF=data.frame(A=c(1,2,1,2,3,2,1,2,3,1,2,3),B=c(2,3,2,2,1,2,3,2,1,2,2,2),C=c(2,3,2,1,1,2,1,1,2,1,2,3))
data_name<-data.frame("A","B","C")
Plot_Graph<-function(x,na.rm=T){
nm=names(x)
for (i in seq_along(nm)) {
print(ggplot(x,aes(x=nm[i],y=x[,i],fill=factor(x[,i]))) +
geom_bar(width=1,stat="identity")+
coord_polar(theta="y")+
ggtitle(data_name[1,i])+
guides(fill=guide_legend(title=NULL))+
scale_fill_discrete(breaks=c('1','2','3'),
labels=c('A','B','C')))}}
Plot_Graph(DF)
However, when I try to create a pie chart for each variable with observations of only '1' and '2' (not selecting '3' for each variable), it gives me the same error every time:
Error: Aesthetics must be either length 1 or the same as the data (1): x, y, fill
I tried the following code:
Plot_Bar<-function(x,na.rm=T){
nm=names(x)
for (i in seq_along(nm)) {
x1<-subset(x,nm[i] %in% c('1','2'))
print(ggplot(x1,aes(x=nm[i],y=x1[,i],fill=factor(x1[,i]))) +
geom_bar(width=1,stat="identity")+
coord_polar(theta="y")+
ggtitle(data_name[1,i])+
guides(fill=guide_legend(title=NULL))+
scale_fill_discrete(breaks=c('1','2'),
labels=c('A','B')))}}
but it did not work. What can I do so as to create an appropriate bar chart for each variable with only observations containing '1' and '2'?
Many thanks.
Your
subset()
isn't correct. If you were to print outx1
you'd see that it's always empty. You can just interchange character values and symbol names in R. You need to use different types of extraction in the two cases. Here's one possible way of re-rewriting the subsetyou can't (easily) use
subset()
when you need to use character strings for column names.