将数学模式下的方程添加到线图中

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

我有以下图,显示两条直线:

library(ggplot2)
x <- seq(0, 600, by = 150)
y1 <- 300 + 0.1 * x
y2 <- 450 + 0.2 * x

data <- data.frame(y1, y2)

z <- ggplot(data, aes(x = x)) +
  geom_line(aes(y = y1), color = "red") +
  geom_line(aes(y = y2), color = "blue") +
  geom_text(aes(x = 0, y = 200, label = "Y_1 = a_1 + 0.1*x = 300 + 0.1*x"), color = "red", hjust = 0, vjust = 1) +
  geom_text(aes(x = 0, y = 100, label = "Y_2 = a_2 + 0.2*x = 450 + 0.2*x"), color = "blue", hjust = 0, vjust = 1) 
z

我想要的是我放在两个标签内的方程,以处于数学模式,最好是乳胶模式。这样我们就可以看到“Y_1”、“Y_2”以及“a_1”和“a_2”的索引。我尝试使用某些回复中所示的表达式,但总是出现错误。有没有一种简单的方法可以实现我所缺少的功能?

ggplot2
1个回答
0
投票

您可以通过配套实现您的目标

latex2exp

library(ggplot2)
x <- seq(0, 600, by = 150)
y1 <- 300 + 0.1 * x
y2 <- 450 + 0.2 * x

data <- data.frame(y1, y2)
library(latex2exp)
z <- ggplot(data, aes(x = x)) +
  geom_line(aes(y = y1), color = "red") +
  geom_line(aes(y = y2), color = "blue") +
  geom_text(aes(x = 0, y = 200), label = TeX("$Y_1 = a_1 + 0.1*x = 300 + 0.1*x$"), color = "red", hjust = 0, vjust = 1) +
  geom_text(aes(x = 0, y = 100), label = TeX("$Y_2 = a_2 + 0.2*x = 450 + 0.2*x$"), color = "blue", hjust = 0, vjust = 1) 
z
© www.soinside.com 2019 - 2024. All rights reserved.