【问题标题】:how to add a fitted distribution to a histogram如何将拟合分布添加到直方图
【发布时间】:2021-04-15 02:56:26
【问题描述】:

我正在尝试向直方图添加一个拟合分布,但是在我运行它之后,它只是一条直线。我怎样才能得到密度线? hist(data$price)lines(density(data$price)), lwd = 2, col ="red")

【问题讨论】:

  • 欢迎来到 SO!这里提出了一个非常相似的问题:stackoverflow.com/questions/1497539/…,如果您在 SO 或 Google 上搜索将密度线(或曲线)添加到直方图,它是最佳结果之一。
  • 您可能还会发现此解决方案很有用,它显示了“平坦”密度曲线的挑战。它使用您已经在使用的相同 hist() 和 lines() 函数提供并排的视觉比较。 stackoverflow.com/questions/58527982/… 为了更好地帮助您解决您的具体问题,请提供示例数据或代码来复制您的数据。

标签: r line


【解决方案1】:

您正在使用graphics 函数hist。改用MASS函数truehist

MASS::truehist(data$price)
lines(density(data$price)), lwd = 2, col ="red")

【讨论】:

    【解决方案2】:

    @Chriss 给出了一个很好的解决方案——它确实在直方图的顶部生成了一条密度曲线;但是,它会更改 y 轴,因此您只能看到密度值(丢失计数值)。

    这是另一种解决方案,它将频率计数放在左侧 y 轴上,并将密度添加为右侧 y 轴。根据需要调整代码,例如 bin、颜色等。我以 mtcars 数据为例,因为问题中没有提供要复制的代码或数据。除了这里使用的两个库(ggpubr 和 cowplot)之外,您可能还需要使用一些 ggplot 函数来更好地自定义这些绘图选项。

    此解决方案的代码已从 https://www.datanovia.com/en/blog/ggplot-histogram-with-density-curve-in-r-using-secondary-y-axis/ 修改

    # packages needed
    library(ggpubr)
    library(cowplot)
    
    # load data (none provided in the original question)
    data("mtcars")
    
    # create histogram (I have 10 bins here, but you may need a different amount)
    phist <- gghistogram(mtcars, x="hp", bins=10, fill="blue", ylab="Count (blue)") + ggtitle("Car Horsepower Histogram")
    
    # create density plot, removing many plot elements
    pdens <- ggdensity(mtcars, x="hp", col="red", size=2, alpha = 0, ylab="Density (red)") +
    scale_y_continuous(expand = expansion(mult = c(0, 0.05)), position = "right")  +
      theme_half_open(11, rel_small = 1) +
      rremove("x.axis")+
      rremove("xlab") +
      rremove("x.text") +
      rremove("x.ticks") +
      rremove("legend")
    
    # overlay and display the plots
    aligned_plots <- align_plots(phist, pdens, align="hv", axis="tblr")
    ggdraw(aligned_plots[[1]]) + draw_plot(aligned_plots[[2]])
    

    【讨论】:

    • 如果您的问题得到了我们中的任何一个人的回答。请通过单击对您最有帮助的答案左侧的复选标记来关闭您的问题。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2018-08-20
    • 2013-11-19
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多