[英]Plot of a Binomial Distribution for various probabilities of success in R
是否可以在R中為彼此相鄰的不同成功概率的二項分布隨機變量繪制類似直方圖的條/線?
試驗次數(n)和樣本空間保持不變。 只有成功的概率(p)是不同的。 為了讓條形彼此相鄰,R代碼看起來如何?
這是一個小例子我的意思:
yval <- 0:10 # sample space
plot(dbinom(yval, 10, 0.5) ~ yval, type = "h", col = "black", ylim = c(0, 0.35))
lines(dbinom(yval, 10, 1/6) ~ yval, type = "h", col = "red")
lines(dbinom(yval, 10, 0.6) ~ yval, type = "h", col = "green")
legend("topright", legend = c("p = 0.5", "p = 1/6", "p = 0.6"),
col = c("black", "red", "green"), lty = 1, cex = 0.7)
使用此代碼,線條相互繪制。 我有什么要改變的?
先感謝您。
你是說如下?
您可以在其他直方圖的x值上添加一個小偏移量:
yval <- 0:10 # sample space
plot(dbinom(yval, 10, 0.5) ~ yval, type = "h", col = "black", ylim = c(0, 0.35))
lines(dbinom(yval, 10, 1/6) ~ I(yval + 0.1), type = "h", col = "red") # + 0.1
lines(dbinom(yval, 10, 0.6) ~ I(yval + 0.2), type = "h", col = "green") # + 0.2
legend("topright", legend = c("p = 0.5", "p = 1/6", "p = 0.6"),
col = c("black", "red", "green"), lty = 1, cex = 0.7)
為了完成我的評論,以下是我們可以用barplot
做的barplot
:
prob <- c(0.5, 1/6, 0.6)
yval <- 0:10
Y <- t(outer(yval, prob, dbinom, size = max(yval)))
barplot(Y, names.arg = yval, beside = TRUE, col = 1:3, border = 1:3,
legend.text = paste0("p = ", format(prob, digits = 2)))
只需將此作為替代方案。
備注1
注意使用上面的outer
。 為什么我們要做額外的t()
? 我們不能這樣做嗎?
Y <- outer(prob, yval, dbinom, size = max(yval))
不會。這會給你很多帶有警告的NaN
。 檢查args(dbinom)
。 函數dbinom
期望yval
在prob
。
備注2
使用barplot
可以輕松地為您產生一些“副作用”,如下所示(這使您更容易比較它們的形狀)。
prob <- c(0.5, 1/6, 0.6)
yval <- 0:10
Y <- outer(yval, prob, dbinom, size = max(yval)) ## no `t()` now
barplot(Y, names.arg = paste0("p = ", format(prob, digits = 2)), beside = TRUE)
使用barplot
col
參數barplot
設置時,使用灰色,其中黑暗與條的高度成比例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.