【问题标题】:How to plot the probability density function graph for multiple data set in 1 graph?如何在一张图中绘制多个数据集的概率密度函数图?
【发布时间】:2019-11-07 16:13:48
【问题描述】:

我为泊松分布生成了 100 个样本,样本大小为 n = 100lambda = 3。现在我正在尝试在同一张图中绘制所有 100 个样本的概率密度函数图。

set.seed(124)


Sample100 <- replicate(100, matrix(data=rpois(100, lambda = 3),ncol = 1), simplify = TRUE)

View(Sample100)

colMeans(Sample100)
apply(Sample100, 2, var)

plot(density(Sample100),xlab = "y", ylab = "P(Y)",main = "Probability density function for 100 sample" )

我从代码中得到的是它只为我提供 1 行假设我将在图中得到 100 行,因为我有 100 组数据

【问题讨论】:

    标签: r


    【解决方案1】:

    如果你熟悉 ggplot 你可以这样做

    set.seed(124)
    library(ggplot2)
    library(tidyr)
    Sample100 <- replicate(100, matrix(data=rpois(100, lambda = 3),ncol = 1), simplify = TRUE)
    Samplelong <- gather(as.data.frame(Sample100))
    
    ggplot(Samplelong, aes(x = value)) +
           geom_density(aes(group = key)) +
           labs(x = "y", #labs function overides labels on the plot
                y = "P(y)",
                title = "Probability density function for 100 sample") +
           theme_classic() +   # This changes the theme to look similar to base r plot theme
           #theme function allows you to modify plot further, everyting from size
           # fonts, angles, axis.
           theme(plot.title = element_text(hjust = 0.5, #hjust - horizontal shift
                                           face = "bold")) + . # face - the print for plot.title is set to bold
           scale_x_continuous(expand = c(0,0))  + #for the continuous x axis, limit expansion to 0 on both ends
           scale_y_continuous(expand = c(0,0)) #for the continuous y axis, limit expansion to 0 on both ends
    

    供参考,您似乎正在绘制以下内容

    ggplot(Samplelong, aes(x = value)) +
           geom_density() +
           labs(x = "y", y = "P(y)", title = "Probability density function for 100 sample") +
           theme_classic() +
           theme(plot.title = element_text(hjust = 0.5)) +
           scale_x_continuous(expand = c(0,0))  +
           scale_y_continuous(expand = c(0,0))
    

    如果 ggplot2 让您感到困惑,请花点时间尝试使图表更漂亮,对于大多数目的来说,以下是可以的。

     ggplot(Samplelong, aes(x = value)) +
       geom_density(aes(group = key)) +
       labs(x = "y", #labs function overides labels on the plot
            y = "P(y)",
            title = "Probability density function for 100 sample")
    

    【讨论】:

    • 确保您已安装并加载了 tidyrggplot2 软件包
    • 我可以像我在原始代码中所做的那样为图表添加 x 和 y 标签和标题吗?
    • 当然,请参阅我的编辑。我包含了更多的功能,使情节看起来尽可能接近经典的情节功能。 ggplot2 是一个很棒的包,需要一些时间来适应如何编辑和修改绘图
    • 从 theme_classic() + theme(plot.title = element_text(hjust = 0.5)) + scale_x_continuous(expand = c(0,0)) + scale_y_continuous(expand = c(0,0) ) 你到底想做什么并没有真正理解代码是如何工作的
    • ggplot 通过向图中“添加”不同的层来工作。我将添加 cmets 来解释每一行对绘图的作用。
    猜你喜欢
    • 2021-01-03
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2011-08-11
    • 2013-01-27
    • 1970-01-01
    相关资源
    最近更新 更多