【发布时间】:2014-09-18 03:20:42
【问题描述】:
在下面的可重现示例中,我尝试动态构建ggplot2 函数调用,以便能够容纳未知数量的混合分布组件。该代码会生成此错误消息:Error in parse(text = g) : <text>:8:0: unexpected end of input。代码有什么问题? (我知道预先计算绘图数据、将其存储在数据框中、将其熔化并提供给ggplot2 的方法。我也想探索下面的选项。)谢谢!
library(ggplot2)
library(scales)
library(RColorBrewer)
library(mixtools)
NUM_COMPONENTS <- 2
set.seed(12345) # for reproducibility
data(diamonds, package='ggplot2') # use built-in data
myData <- diamonds$price
calc.component <- function(x, lambda, mu, sigma) {
lambda * dnorm(x, mean = mu, sd = sigma)
}
overlayHistDensity <- function(data, func) {
# extract 'k' components from mixed distribution 'data'
mix <- normalmixEM(data, k = NUM_COMPONENTS,
maxit = 100, epsilon = 0.01)
summary(mix)
DISTRIB_COLORS <-
suppressWarnings(brewer.pal(NUM_COMPONENTS, "Set1"))
# plot histogram, empirical and fitted densities
g <- "ggplot(data) +\n"
for (i in seq(length(mix$lambda))) {
args <- paste0("args.", i)
assign(args, list(lambda = mix$lambda[i], mu = mix$mu[i],
sigma = mix$sigma[i]))
g <- paste0(g,
"stat_function(fun = func, args = ",
args,
", aes(color = ",
DISTRIB_COLORS[i], ")) +\n")
}
tailStr <-
"geom_line(aes(y = ..density..,colour = 'Empirical'),stat = 'density') +
geom_histogram(aes(y = ..density..), alpha = 0.4) +
scale_colour_manual(name = '', values = c('red', 'blue')) +
theme(legend.position = 'top', legend.direction = 'horizontal')"
g <- paste0(g, tailStr)
gr <- eval(parse(text = g))
return (gr)
}
overlayHistDensity(log10(myData), 'calc.component')
【问题讨论】: