我正在制作一个出版物,希望用一些beta和p值来注释它;我所在地区的风格指南要求这些数字的格式不带前导零(例如," .003",不是" 0.003")。我遇到了似乎是Catch-22的东西;我从我的模型中提取了beta和p值,并进行了一些预处理以正确格式化它们,以便它们现在是字符而不是数字:
fake.beta.vals <- c(".53", ".29", ".14")
fake.p.vals <- c(".034", ".001", ".050")
但是,当我尝试在我的图中使用这些值时,parse = TRUE
会将它们变回数值,从而失去我需要的格式。
fake.beta.vals <- c(".53", ".29", ".14")
fake.p.vals <- c(".034", ".001", ".050")
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width))
p <- p +
geom_smooth(method = "lm") +
geom_point() +
facet_wrap( ~ Species)
p
len <-length(levels(iris$Species))
vars <- data.frame(expand.grid(levels(iris$Species)))
colnames(vars) <- c("Species")
betalabs <- as.data.frame(fake.beta.vals)
plabs <- as.data.frame(fake.p.vals)
dat <- data.frame(
x = rep(7, len),
y = rep(4, len),
vars,
betalabs,
plabs)
dat$fake.beta.vals <- as.factor(dat$fake.beta.vals)
dat$fake.p.vals <- as.factor(dat$fake.p.vals)
p <- p +
geom_text(
aes(x = x,
y = y,
label = paste("list(beta ==",
fake.beta.vals,
", italic(p) ==",
fake.p.vals,
")"),
group = NULL),
size = 5,
data = dat,
parse = TRUE)
p
我一直在讨论这个问题一段时间但是添加了as.character()
:
label = paste("list(beta ==",
as.character(fake.beta.vals),
", italic(p) ==",
as.character(fake.p.vals),
")"),
显然也被parse = TRUE
添加我以前用来格式化我的值的函数:
statformat <- function(val,z){
sub("^(-?)0.", "\\1.", sprintf(paste("%.",z,"f", sep = ""), val))
}
更糟糕的是:
label = paste("list(beta ==",
statformat(fake.beta.vals, 2),
", italic(p) ==",
statformat(fake.p.vals, 3),
")"),
最后一团糟。
帮助?
答案 0 :(得分:6)
使用bquote
创建标签,然后使用deparse
强制转换为字符代表
例如
# create a list of labels using bquotw
labs <- Map(.beta = fake.beta.vals,
.p = fake.p.vals,
f = function(.beta,.p) bquote(list(beta == .(.beta), italic(p) == .(.p))))
# coerce to a character representation for parse=TRUE to work within
# geom_text
dat <- data.frame(
x = rep(7, len),
y = rep(4, len),
vars,
labels = sapply(labs,deparse))
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_smooth(method = "lm") +
geom_point() +
facet_wrap( ~ Species) +
geom_text(data = dat, aes(x=x,y=y,label=labels), parse=TRUE)
p
答案 1 :(得分:5)
回到我的电脑并重新阅读你的问题后,我发现我误解了这个问题。试用I
函数,我发现它似乎不适用于parse
。
我找到了一种方法让它发挥作用,这是通过将fake.beta.vals
和fake.p.vals
包含在您的解析调用中的`字符或'字符。
p <- p +
geom_text(
aes(x = x,
y = y,
label = paste("list(beta ==",
"`", fake.beta.vals, "`",
", italic(p) ==",
"`", fake.p.vals, "`",
")",
sep=""),
group = NULL),
size = 5,
data = dat,
parse = TRUE)
那应该有用。