箱线图似乎不一定是可视化此二进制数据的最佳方式。以下是一些示例,您可以如何绘制该数据并对价格与正面评分比例之间的线性相关性进行简单分析。
# approximation of your data
mydf <- data.frame(meat=LETTERS[1:3], price=c(100, 23, 45),
posR=c(23,2,6), negR=c(4,1,0))
# consider a barplot to show ratings:
barplot(cbind(posR, negR) ~ meat, data=mydf, col=c(2,1))
legend("topright", c("positive", "negative"), fill = c(2,1))
mydf$fracPos <- with(mydf, posR/(posR + negR))
# plot positive fraction
with(mydf, barplot(cbind(fracPos, 1-fracPos) ~ meat, data=mydf, col=c(2,1)))
legend("right", c("positive", "negative"), fill = c(2,1))
# calculate pearson correlation
lm1 <- lm(fracPos ~ price, data=mydf)
# plot average rating over price, add trendline and p-value of correlation
plot(fracPos ~ price, data=mydf,
sub=paste0("p=", sprintf("%.3g", summary(lm1)[[4]][[8]]), "; R.sq=",
sprintf("%.3g", summary(lm1)$r.squared)))
abline(coef(lm1), col="red")
如果您仍想绘制箱线图,请记住,中位数只能是该系统中的一个或另一个二进制值。我们也在这里确定平均值并绘制它。在此示例中,正面评级被指定为 +1 值,负面评级为 -1。
# generating ratings vectors with +1 for pos and -1 for each neg rating
mydf$ratings <- apply(mydf, 1, function(x) c(rep(1, x[["posR"]]), rep(-1, x[["negR"]])))
# calculate mean rating
mydf$avgR <- sapply(mydf$ratings, mean)
# show boxplots with mean as a red dot
with(mydf, boxplot(setNames(ratings, meat)))
points(mydf$avgR, col="red", pch=18)
由reprex package (v0.3.0) 于 2021-01-04 创建