【问题标题】:density curve over plotly histogramplotly 直方图上的密度曲线
【发布时间】:2016-12-28 19:36:00
【问题描述】:

我正在使用 plotly 为我正在使用的数据集绘制直方图

test  <- data.frame(y = rgamma(1000, shape = 0.25, rate = 0.0054))
plot_ly(x = ~test$y, type = "histogram", nbinsx = "23")

这样的图很好,但我不清楚如何绘制一条流过直方图轮廓的平滑密度曲线。

阴谋reference manual建议,

使用 plot_ly 或 add_trace 初始化直方图轨迹:

plot_ly(df, type="histogram"[, ...])
add_trace(p, type="histogram"[, ...]) 

还有一个histnorm (enumerated: "" | "percent" | "probability" | "density" | "probability density" ) histonorm 函数,我假设它允许用户绘制密度曲线,但我不知道如何使用这个函数。

有兴趣了解其他人是如何解决这个问题的。非常感谢任何提示或建议。

【问题讨论】:

  • 我想知道是否有一种方法可能是scale密度,以便在情节上更加清晰。 test = data.frame(y = rgamma(1000, shape = 0.25, rate = 0.0054)) ; fit = density(test$y) ; scale = 500/max(fit$y) ; plot_ly() %&gt;% add_histogram(x = ~test$y, name = "Histogram") %&gt;% add_lines(x = fit$x, y = scale*fit$y, name = "Density")
  • @DarshanBaral 这很有趣

标签: r plot overlay plotly density-plot


【解决方案1】:

虽然不理想 - 这是一种方法。

编辑:针对 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))

【讨论】:

  • x 轴上有一条额外的线可能是由于密度图
【解决方案2】:

如果您对 ggplot 的 API 比对 plotly 的更熟悉(就像我一样),那么最简单的一个选择是首先使用 ggplot2 进行绘图。

library(plotly)
library(ggplot2
test  <- data.frame(y = rgamma(1000, shape = 0.25, rate = 0.0054))

p <- ggplot(test, aes(x = y, y = ..density..)) +
   geom_histogram(fill = "steelblue", bins  = 23) +
   geom_density()

ggplotly(p)

【讨论】:

  • 我试过 ggplot 但我无法抑制密度图产生的 y 轴值并显示直方图中的频率计数。
猜你喜欢
  • 2021-02-04
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
相关资源
最近更新 更多