Home > Software engineering >  Adding a title to a plot that was made in an R function
Adding a title to a plot that was made in an R function

Time:03-12

I made a function that graphs the competition model between owls and hawks. I want to have different titles for each plot. Can I add a title after it has been plotted or do I need to get rid of the function and plot individually? Ideally, I would like to keep as a function. Thank you in advance!

```{r}
#setting x axis, days
x <- c(0:30)

#function that takes initial conditions and calculates from 1 to 30 days
comp <- function(o, h, x){
  for (j in 1:30){
    on = 0.2*o[j] - .001*h[j]*o[j]   o[j]
    hn = 0.3*h[j] - .002 *h[j]*o[j]   h[j]
    o <- append(o, on)
    h <- append(h, hn)
    }
  plot(x, o, col="blue", type="l", ylim=range(c(o,h)), xlab="X", ylab="On, Hn", pch=8)
lines(x, h, col="red", type="l", pch=10)
legend("topleft", legend=c("Owls", "Hawks"),
       col=c("red", "blue"), lty=1:2, cex=0.8)
}


comp(151, 199, x) 
comp(149, 201, x)
comp(10, 10, x)
```

CodePudding user response:

You could add arguments to your function including title. Alternatively, you could use ggplot2, which allows you to add or modify many components of your graphs. The following code roughly reproduce your function with ggplot2:

library(tidyverse)
x <- c(0:30)
comp_2 <- function(o, h, x){
  for (j in 1:30){
    on = 0.2*o[j] - .001*h[j]*o[j]   o[j]
    hn = 0.3*h[j] - .002 *h[j]*o[j]   h[j]
    o <- append(o, on)
    h <- append(h, hn)
  }
data.frame(x = x, o = o, h = h) %>% 
  ggplot(aes(x = x))   
  geom_line(aes(y = o, col="Owls"))   
  geom_line(aes(y =h, col="Hawks"))  
  theme_bw() 
 labs(x = "X", y="On, Hn")   
  theme(legend.title = element_blank(), 
        legend.position = c(0.1, 0.8))
}
comp_2(151, 199, x)   labs(title = "Figure 1") # add others if needed
comp_2(149, 201, x)   labs(title = "Figure 2")
comp_2(10, 10, x)   labs(title = "Figure 3")
  • Related