I am trying to use ggplot2 to create multiple graphs for my data using a for loop. For this I am trying to print the ggplot object which returns an error
Error in
[.data.frame(df, , (i)) : undefined columns selected .
Also I am unable to get a legend to be printed on the graph. If I don't print it shows a single chart.
for(i in seq(from=2, to=ncol(pvp), by=4)){
sq= as.numeric(c(1,(i):(i+3)))
print(sq)
df=pvp[,sq]
print(head(df))
colordf=colnames(df)[((i):(i+3))]
p=ggplot(df,aes(x=df$tot_urls_read)) +
geom_line(aes(y=df[,(i)]),color="red")
p=p+ geom_line(aes(y=df[,(i+1)]),color="green")
p=p+ geom_line(aes(y=df[,(i+2)]),color="blue")
p=p+ geom_line(aes(y=df[,(i+3)]),color="black") +
xlab("Percentage") +
ylab("Pvs") +
scale_fill_identity(name = '', guide = 'legend',labels = colordf) +
scale_colour_manual(name = 'Topic lines', values =c('red'='red','green'='green','blue'='blue','black'='black'),
labels = colordf)
print(p)
}
This is a part of my data . There are more columns in it
tot_urls_read Andhra Goa Maharashtra Karnataka UP MP West Bengal Assam
1 1 1 100.00000 100.00000 100.00000 100.00000 100.00000 100.00000 100.00000 100
2 2 2 51.28552 50.25325 50.00000 50.00000 50.00000 51.95487 50.70178 50
3 3 3 34.70799 33.67254 33.33333 33.33333 33.33333 35.23031 33.90084 33
4 4 4 26.28165 25.26571 25.00000 25.00000 25.00000 26.73067 25.36423 25
5 5 5 21.18226 20.31540 20.00000 20.00000 20.00000 21.62096 20.48651 22
6 6 6 17.83460 16.92501 16.66667 16.66667 16.76647 18.20869 16.99758 16
How can I use a for loop to create multiple charts and also give a header? I don't have a hang of this and seem to be all over the place.
Any Help is greatly appreciated.

df=pvp[,sq]creates a 5-column data.frame ; then, you try to usedf[,i]whereimight be > 5. Replace alldf[,i]bydf[,2],df[,i+1]bydf[,3], etc.