为在 R 函数中绘制的绘图添加标题
Adding a title to a plot that was made in an R function
我做了一个函数来绘制猫头鹰和鹰之间的竞争模型。我想为每个情节设置不同的标题。我可以在绘制后添加标题,还是需要摆脱功能并单独绘制?理想情况下,我想保留一个功能。提前致谢!
```{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)
```
您可以向函数添加参数,包括标题。或者,您可以使用 ggplot2
,它允许您添加或修改图形的许多组件。以下代码使用 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")
我做了一个函数来绘制猫头鹰和鹰之间的竞争模型。我想为每个情节设置不同的标题。我可以在绘制后添加标题,还是需要摆脱功能并单独绘制?理想情况下,我想保留一个功能。提前致谢!
```{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)
```
您可以向函数添加参数,包括标题。或者,您可以使用 ggplot2
,它允许您添加或修改图形的许多组件。以下代码使用 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")