3 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
stat_function旨在在每個(gè)面板中覆蓋相同的功能。(沒(méi)有明顯的方法可以使函數(shù)的參數(shù)與不同的面板匹配)。
正如伊恩(Ian)所建議的那樣,最好的方法是自己生成法線,并將其繪制為單獨(dú)的數(shù)據(jù)集(這是您之前出錯(cuò)的地方-合并對(duì)于這個(gè)示例來(lái)說(shuō)沒(méi)有意義,如果仔細(xì)看,您會(huì)看到這就是為什么您會(huì)得到奇怪的鋸齒圖案)。
解決問(wèn)題的方法如下:
dd <- data.frame(
predicted = rnorm(72, mean = 2, sd = 2),
state = rep(c("A", "B", "C"), each = 24)
)
grid <- with(dd, seq(min(predicted), max(predicted), length = 100))
normaldens <- ddply(dd, "state", function(df) {
data.frame(
predicted = grid,
density = dnorm(grid, mean(df$predicted), sd(df$predicted))
)
})
ggplot(dd, aes(predicted)) +
geom_density() +
geom_line(aes(y = density), data = normaldens, colour = "red") +
facet_wrap(~ state)

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
我認(rèn)為您需要提供更多信息。這似乎可行:
pg <- ggplot(dd, aes(Predicted_value)) ## need aesthetics in the ggplot
pg <- pg + geom_density()
## gotta provide the arguments of the dnorm
pg <- pg + stat_function(fun=dnorm, colour='red',
args=list(mean=mean(dd$Predicted_value), sd=sd(dd$Predicted_value)))
## wrap it!
pg <- pg + facet_wrap(~State_CD)
pg
我們?yōu)槊總€(gè)面板提供相同的均值和sd參數(shù)。讀者可以練習(xí)獲得面板特定的平均值和標(biāo)準(zhǔn)偏差*;)
'*'換句話說(shuō),不確定如何完成...

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您不想“手工”生成正態(tài)分布線圖,仍要使用stat_function并排顯示圖形-那么您可以考慮使用在“ Cookbook for R”上發(fā)布的“ multiplot”函數(shù)替代facet_wrap。您可以從此處將多圖代碼復(fù)制到您的項(xiàng)目中。
復(fù)制代碼后,請(qǐng)執(zhí)行以下操作:
# Some fake data (copied from hadley's answer)
dd <- data.frame(
predicted = rnorm(72, mean = 2, sd = 2),
state = rep(c("A", "B", "C"), each = 24)
)
# Split the data by state, apply a function on each member that converts it into a
# plot object, and return the result as a vector.
plots <- lapply(split(dd,dd$state),FUN=function(state_slice){
# The code here is the plot code generation. You can do anything you would
# normally do for a single plot, such as calling stat_function, and you do this
# one slice at a time.
ggplot(state_slice, aes(predicted)) +
geom_density() +
stat_function(fun=dnorm,
args=list(mean=mean(state_slice$predicted),
sd=sd(state_slice$predicted)),
color="red")
})
# Finally, present the plots on 3 columns.
multiplot(plotlist = plots, cols=3)
- 3 回答
- 0 關(guān)注
- 2491 瀏覽
添加回答
舉報(bào)