使用ggplot2在R中标记线性函数

问题描述 投票:0回答:1

我有以下代码:

v1 <- function(x){x/0.5-0.5}
v2 <- function(x){x/0.3-0.5}

library("ggplot2")


p <- ggplot(data.frame(x=c(0,1)), aes(x=x)) 

p +
  stat_function(fun=v1, geom="line") + 
  stat_function(fun=v2, geom="line") + 
  xlab("θ") + ylab("v(θ)") +
  theme_classic()

[执行代码时,我希望将生成的函数分别标记为v1v2。如何获得理想的结果?

r ggplot2 plot label
1个回答
0
投票

怎么样?

p +
  stat_function(fun=v1, geom="line") + 
  stat_function(fun=v2, geom="line") + 
  xlab("θ") + ylab("v(θ)") +
  theme_classic()+
  annotate("text",x=0.5,y=v1(0.5)-0.2,label="v1")+
  annotate("text",x=0.5,y=v2(0.5)+0.2,label="v2")
© www.soinside.com 2019 - 2024. All rights reserved.