添加 ggplot2 选项 geom_hline 作为字符串
Add ggplot2 option geom_hline as string
我有一个关于 ggplot2 的问题。抱歉,因为函数是在 shiny 中调用的,所以没有给出示例数据。如果需要,我将尝试构建一个没有闪亮代码的最小示例。但我希望这个问题可能很简单,并且无需重新运行代码就可以得到答案。
我尝试为 ggplot 函数提供几个 geom_hline
选项,这些选项在 for 循环内创建为字符串。 struct$Retention
是几个数值。
问题是 eval(parse(text = horizLine))
尝试评估字符串,因此尝试添加 +
个字符串,这会导致以下错误:
Warning: Error in +: non-numeric argument to binary operator
Stack trace (innermost first):
78: eval [<text>#1]
77: eval
76: renderPlot [plots.R#11]
68: output$ClaimPlot
1: runApp
所以我正在寻找的是一种将带有 +
函数的字符串作为 ggplot 函数的选项的方法。
或另一种为 ggplot 提供选项的方法。
output$ClaimPlot <- renderPlot({
x <- readClaimData()
struct <- readStructData()
horizLine <- c()
for( i in 1:length( struct$Retention )) {
horizLine[i] <- paste("geom_hline(aes(yintercept =", as.numeric(struct$Retention[i]), "))", sep = "")
}
horizLine <- paste(horizLine, sep = "", collapse = " + ")
x <- melt(x, id.vars = c("Year", "ClaimNo"), variable.name = "State", value.name = c("Claim"))
ggplot(data = x, aes(x=factor(ClaimNo), y=Claim, fill = factor(State))) +
geom_bar(colour = "black", stat = "identity") +
ylab("Claim Size") +
xlab("Claim Number") +
facet_grid(Year ~ .) +
eval(parse(text = horizLine))
})
有什么原因不能将 struct
数据帧传递给 geom_hline
?
像这样:
ggplot(data = x, aes(x=factor(ClaimNo), y=Claim, fill = factor(State))) +
geom_bar(colour = "black", stat = "identity") +
ylab("Claim Size") +
xlab("Claim Number") +
facet_grid(Year ~ .) +
geom_hline(data=struct, aes(yintercept=Retention))
根据您要查找的内容,您可能需要向 struct
添加其他信息(即年份?)
我有一个关于 ggplot2 的问题。抱歉,因为函数是在 shiny 中调用的,所以没有给出示例数据。如果需要,我将尝试构建一个没有闪亮代码的最小示例。但我希望这个问题可能很简单,并且无需重新运行代码就可以得到答案。
我尝试为 ggplot 函数提供几个 geom_hline
选项,这些选项在 for 循环内创建为字符串。 struct$Retention
是几个数值。
问题是 eval(parse(text = horizLine))
尝试评估字符串,因此尝试添加 +
个字符串,这会导致以下错误:
Warning: Error in +: non-numeric argument to binary operator
Stack trace (innermost first):
78: eval [<text>#1]
77: eval
76: renderPlot [plots.R#11]
68: output$ClaimPlot
1: runApp
所以我正在寻找的是一种将带有 +
函数的字符串作为 ggplot 函数的选项的方法。
或另一种为 ggplot 提供选项的方法。
output$ClaimPlot <- renderPlot({
x <- readClaimData()
struct <- readStructData()
horizLine <- c()
for( i in 1:length( struct$Retention )) {
horizLine[i] <- paste("geom_hline(aes(yintercept =", as.numeric(struct$Retention[i]), "))", sep = "")
}
horizLine <- paste(horizLine, sep = "", collapse = " + ")
x <- melt(x, id.vars = c("Year", "ClaimNo"), variable.name = "State", value.name = c("Claim"))
ggplot(data = x, aes(x=factor(ClaimNo), y=Claim, fill = factor(State))) +
geom_bar(colour = "black", stat = "identity") +
ylab("Claim Size") +
xlab("Claim Number") +
facet_grid(Year ~ .) +
eval(parse(text = horizLine))
})
有什么原因不能将 struct
数据帧传递给 geom_hline
?
像这样:
ggplot(data = x, aes(x=factor(ClaimNo), y=Claim, fill = factor(State))) +
geom_bar(colour = "black", stat = "identity") +
ylab("Claim Size") +
xlab("Claim Number") +
facet_grid(Year ~ .) +
geom_hline(data=struct, aes(yintercept=Retention))
根据您要查找的内容,您可能需要向 struct
添加其他信息(即年份?)