【发布时间】:2019-08-14 16:19:12
【问题描述】:
我正在尝试使用this 答案的组合将方程注释到ggplot 图和this 答案的组合,将不同的文本放在不同的方面。
我遇到的问题是我无法在不同方面使用数学表达式得到不同的公式。
#Required package
library(ggplot2)
#Split the mtcars dataset by the number of cylinders in each engine
cars.split <- split(mtcars, mtcars$cyl)
#Create a linear model to get the equation for the line for each cylinder
cars.mod <- lapply(cars.split, function(x){
lm(wt ~ mpg, data = x)
})
#Create predicted data set to add a 'geom_line()' in ggplot2
cars.pred <- as.data.frame(do.call(rbind,
mapply(x = cars.split, y = cars.mod,
FUN = function(x, y){
newdata <- data.frame(mpg = seq(min(x$mpg),
max(x$mpg),
length.out = 100))
pred <- data.frame(wt = predict(y, newdata),
mpg = newdata$mpg)
}, SIMPLIFY = F)))
cars.pred$cyl <- rep(c(4,6,8), each = 100)
(cars.coef <- as.data.frame(do.call(rbind, lapply(cars.mod, function(x)x$coefficients))))
#Create a data frame of line equations a 'cyl' variable to facilitate facetting
#as per second link. I had to MANUALLY take the values 'cars.coef' and put them
#into the data frame.
equation.text <- data.frame(label = c('y = 4.69-0.09x^{1}',
'y = 6.42-0.17x^{1}',
'y = 6.91-0.19x^{1}'),
cyl = c(4,6,8))
#Plot it
ggplot(data = mtcars, mapping = aes(x = mpg, y = wt)) +
geom_point() +
geom_line(data = cars.pred, mapping = aes(x = mpg, y = wt)) +
geom_text(data = equation.text, mapping = aes(x = 20, y = 5, label = label)) +
facet_wrap(.~ cyl)
图中的方程与我在equation.text 数据框中所写的完全一样,这并不奇怪,因为方程在'' 中。但我试图让它用数学符号表示,比如 $y = 4.69–0.09x^1$
我知道我需要使用expression,正如我在first link 中所说的那样,但是当我尝试将它放入数据框时:
equation.text <- data.frame(label = c(expression(y==4.69-0.9*x^{1}),
expression(y==6.42-0.17*x^{1}),
expression(y==6.91-0.19*x^{1})),
cyl = c(4,6,8))
我收到一条错误消息,提示 expressions 无法放入数据帧中:
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class '"expression"' to a data.frame
我的问题是:
- 如何在不同方面获得不同数学符号(斜体字母、上标、下标)的方程?
- 从
cars.coef数据框中获取值到equations表中的更自动化的方法是什么(而不是输入所有数字!)? - 更新:This 引起了我的注意,但很多答案似乎都适用于线性模型。有没有办法为非线性模型做这件事?
【问题讨论】:
-
+1 用于明确解释并展示研究成果的可重现问题!这可能解决不了任何问题,但是为什么
equation.text内部有==而不是=? -
在我第二次尝试方程式文本时,使用了
==,因为当在expression中使用然后作为annotation添加到绘图中时,它只是以“=”的形式出现而不是“==”,因为expression会将函数内部的任何内容(如果您知道自己在做什么,恐怕我不知道)转换为数学符号的公式。
标签: r ggplot2 expression