2016-12-28 215 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軸上有一條額外的線可能是由於密度圖 –

相關問題