2016-12-28 210 views
0

我使用plotly绘制一个数据集的直方图我与密度曲线上plotly直方图

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

情节本身是好的,但我不清楚如何绘制流过一个光滑的密度曲线工作直方图的轮廓。

Plotly reference manual表明,

直方图迹被初始化plot_ly或add_trace

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

和有我假设将允许用户绘制的密度曲线histnorm (enumerated: "" | "percent" | "probability" | "density" | "probability density") histonorm功能,但我不知道如何使用这个功能。

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

+1

我不知道如果一个方法可能是'scale'密度,使其上的情节更加清晰。 'test = data.frame(y = rgamma(1000,shape = 0.25,rate = 0.0054)); fit = density(test $ y); scale = 500/max(fit $ y); plot_ly()%>%add_histogram(x =〜test $ y,name =“直方图”)%>%add_lines(x = fit x,y = scale * fit $ y,name =“Density”)' –

+0

@DarshanBaral这很有趣 –

回答

0

一个选项,如果你比gigplot的API更熟悉,那么最简单的方法就是先用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) 

enter image description here

+0

我试过ggplot,但我无法抑制密度图产生的y轴值,并显示直方图的频率计数。 –

0

虽然不理想 - 这里的做到这一点的方法之一。

编辑:更新的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)) 
+0

x轴上有一条额外的线可能是由于密度图 –

相关问题