Continuously add lines to ggplot with for loop
2
1
Entering edit mode
7.8 years ago
frcamacho ▴ 210

Hi there,

I have an object called gPlot and I want to continuously add geom_lines to the gPlot object.

# df is a dataframe
sstart ssend
167    2637
552    8273

My following code is :

gPlot<-ggplot() + geom_line(aes(x=1:6549, y=1, colour="red")) + geom_line(aes(x=295:1218, y=.99, colour="blue")) + geom_line(aes(x=3084:4340, y=.99, colour="green"))+coord_cartesian(xlim = c(0, 6549), ylim = c(0,1)) +  xlab("coordinates") + ylab("regions")

geomLine <- NULL
for(i in 1:nrow(df)){
  rowDF<-df[i,]
  dfstart <-rowDF$sstart
  dfend<-rowDF$send
  geomLine<-gPlot+geom_line(aes(x=dfstart:dfend, y=.95, colour="black"))
}

However, when I plot the new ranges from the df, the plot does not add all the ranges but, just puts the last number range. Any help would be appreciated.

Thanks!

R ggplot2 • 19k views
ADD COMMENT
0
Entering edit mode

did you find the reason why this happen in the for loop?

ADD REPLY
6
Entering edit mode
7.8 years ago
frcamacho ▴ 210

I finally solved the above question after staring at the computer. Using aes_string() made it work.

for(i in 1:nrow(stool_polyketide_analysis_df_vfam)){
  rowDF<-stool_polyketide_analysis_df_vfam[i,]
  dfstart <-rowDF$sstart
  dfend<-rowDF$send
  gPlot<-gPlot+geom_line(aes_string(x=dfstart:dfend, y=.95-.005*i))
}
ADD COMMENT
3
Entering edit mode

Believe it or not, this is the best answer to solving the looping problem with ggplot. Most of the answers have a lot of elaborate schemes that I was not able to get to work. This simple one works!! Thanks

ADD REPLY
0
Entering edit mode

thank you, one-week struggle finally solved

ADD REPLY
0
Entering edit mode

"after staring at the computer" ... lfmao

ADD REPLY
0
Entering edit mode
4 months ago

I think the answer is very simple, do not use an aes call. The updated code should look as below:

gPlot<-ggplot() + geom_line(aes(x=1:6549, y=1, colour="red")) + geom_line(aes(x=295:1218, y=.99, colour="blue")) + geom_line(aes(x=3084:4340, y=.99, colour="green"))+coord_cartesian(xlim = c(0, 6549), ylim = c(0,1)) +  xlab("coordinates") + ylab("regions")

geomLine <- NULL
for(i in 1:nrow(df)){
  rowDF<-df[i,]
  dfstart <-rowDF$sstart
  dfend<-rowDF$send
  geomLine<-gPlot + 
  geom_line(x=dfstart:dfend, y=.95, colour="black") # new addition
}
ADD COMMENT

Login before adding your answer.

Traffic: 2655 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6