R - 间歇性 Missig 条形图 ggplot

R - Intermittent Missig Bar Plot ggplot

我 运行 在使用 ggplot 函数在 r 中开发直方图和几何条形图时遇到了缺少图形的问题。该问题是间歇性的,并且出现在多个数据集中。这里描述了一个最大的数据集。

我的初始代码,用于生成 运行domized 数据,是这样的:

Nruns <- 15

# output structure as a list for convenience
out_structure <- vector( "list", Nruns )

for ( i_dice in seq_len( Nruns ) ) {
 # Number of Successes for y rolls -- rolls = 1
 Num.Dice <- i_dice # number of dic

 sr. <- as.numeric() # create empty vector -- ShadowRun 15 dice
 for(i in 1:500000) {
   sr.[(i:i)] <- sum(sample(1:6, Num.Dice, replace=TRUE)>=5)
 }

 out_structure[[i_dice]] <- sr.
}  

sr.1to15 <- as.data.frame(out_structure, 
                         col.names = paste0("sr.", seq_len( Nruns )))

这会根据 500000 个样本生成 15 个变量,计算结果 1 到 6。

我的ggplot代码是这样的:

library(ggplot2)
library(scales)

ggplot(sr.1to15) + 
 aes(sr.15) +
 geom_bar(aes(y = (..count..)/sum(..count..))) +
 scale_x_continuous(breaks = seq(1:15), lim = c(0, 15)) + 
 scale_y_binned(labels = percent_format(accuracy = 1)) 

或者这个;取决于我检查的其他变量(这里是同一代码的两次连续传递):

尝试解决此问题:

(1) 退出 R. 重新打开 R.

(2) 关闭笔记本电脑。再次打开笔记本电脑。

(3) 已尝试删除所有对象和包。

(4) 通过 rstudio 界面清理全局环境。

remove(list = ls())

None 次尝试纠正了错误。

注意:以下代码始终有效:

hist(sr.1to15$sr.15) [此处未显示]

我当前的图书馆是:


> my_packages <- library()$results[,1]
> head(my_packages, 10)
 [1] "abind"      "ade4"       "askpass"    "assertthat" "backports" 
 [6] "base64enc"  "BH"         "blob"       "broom"      "callr" 

如何让 ggplot 始终如一地工作?

问题是您正在使用 scale_y_binned()。其余代码对我来说工作正常,除非我将此特定行添加到绘图中。 “分箱”正在工作(您的 y 轴有 %),但您看不到几何图形,因为最终,ggplot2 正在使用用于 geom_bar/geom_col 的相同几何图形绘制直方图.此几何 需要 连续的 y 轴,并且 scale_y_binned() is designed to "bin" or "discretize" the y axis。所以...在两个图表上都绘制了条形图,但是一旦合并,ggplot2 就不知道如何绘制几何图形了。

至于为什么您会看到不一致...不确定。有时执行代码需要时间。当我 运行 你的代码时,它总是给我第二张图表(没有条)。

要修复,您需要使用 scale_y_continuous() 并设置标签。

ggplot(sr.1to15) + 
  aes(sr.15) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  scale_x_continuous(breaks = seq(1:15), lim = c(0, 15)) +
  scale_y_continuous(labels = percent_format(accuracy = 1))