使用 ggplot2 的密度图

Density graph using ggplot2

我创建了一个掷骰子模拟器并生成了一些数据。我正在查看给定掷骰数的赢与输的概率。这是我的数据的前 25 个结果,其余的看起来完全一样(只有 50,000 行长):

这是我用来用我的数据创建密度图的代码:

ggplot(df, aes(x=rollCount, fill = winOrLoss)) + 
    #geom_histogram(binwidth = 1, position = "identity", alpha=0.6) +
    scale_y_sqrt() +
    scale_x_continuous(limits=c(1, 32), breaks=1:32) +
    labs(title="Roll Count Histogram", x="Roll Count", y="Count") +
    geom_hline(aes(yintercept=0)) +
    geom_density()

这是结果图:

我希望密度图看起来像这样:

我的主要问题是如何让它变得更加平滑,而不是目前看起来的上下波动。在将数据放入图表之前,我需要对数据做些什么吗?我只是将它放入带有 df <- data.frame(rollCount, winOrLoss) 的数据框中,让 ggplot 处理其余部分。

你有一个离散分布。 stat_density 假设连续分布。使用 geom_histogram 代替:

set.seed(42)
rollCount <- sample(1:20, 50, TRUE, prob = 20:1)
winOrLoss <- sample(c("W", "L"), 50, TRUE)
DF <- data.frame(rollCount, winOrLoss)

library(ggplot2)
ggplot(DF, aes(x=rollCount, fill = winOrLoss)) + 
  geom_histogram(binwidth = 1, position = "identity", alpha=0.6, 
                 aes(y = ..density..))