问题描述
我正在使用 plotly 为我正在使用的数据集绘制直方图
I am using plotly to plot a histogram for a dataset I am working with
test <- data.frame(y = rgamma(1000, shape = 0.25, rate = 0.0054))
plot_ly(x = ~test$y, type = "histogram", nbinsx = "23")
这样的图很好,但我不清楚如何绘制流经直方图轮廓的平滑密度曲线.
The plot as such is fine but I am unclear how to draw a smooth density curve flowing through the contours of the histogram.
Plotly 参考手册建议,
使用 plot_ly 或 add_trace 初始化直方图轨迹:
A histogram trace is initialized with plot_ly or add_trace:
plot_ly(df, type="histogram"[, ...])
add_trace(p, type="histogram"[, ...])
并且有一个 histnorm(枚举:"|百分比"|概率"|密度"|概率密度")
histonorm 函数,我认为它允许用户绘制密度曲线,但我不知道如何使用这个功能.
and there is a histnorm (enumerated: "" | "percent" | "probability" | "density" | "probability density" )
histonorm function which i assume will allow users to draw a density curve but I am not sure how to use this function.
有兴趣了解其他人是如何解决这个问题的.非常感谢任何提示或建议.
Interested to find out how others have approached this problem. Any tips or suggestions are much appreciated.
推荐答案
虽然不理想 - 这是一种方法.
While not ideal - here's one way to do it.
更新了 y 轴限制
library(plotly)
y <- rgamma(1000, shape = 0.25, rate = 0.0054)
dens <- data.frame(x = density(y)$x,
y = density(y)$y)
miny <- 0
maxy <- max(dens$y)
plot_ly() %>%
add_histogram(x = y) %>%
add_lines(data = dens, x = ~x, y = ~y, yaxis = "y2",
line = list(width = 3)) %>%
layout(yaxis2 = list(overlaying = "y",
side = "right",
range = c(miny, maxy),
showgrid = F,
zeroline = F))
这篇关于图直方图上的密度曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!