Histograms in ggplot2
How to make Histogram Plots in ggplot2 with Plotly.
Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Sign up for early access now.
Basic Histogram
library(plotly)
dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))
p <- ggplot(dat,aes(x=xx)) +
geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)
ggplotly(p)
Click to copy
Add Lines
library(plotly)
df1 <- data.frame(cond = factor( rep(c("A","B"), each=200) ),
rating = c(rnorm(200),rnorm(200, mean=.8)))
df2 <- data.frame(x=c(.5,1),cond=factor(c("A","B")))
p <- ggplot(data=df1, aes(x=rating, fill=cond)) +
geom_vline(xintercept=c(.5,1)) +
geom_histogram(binwidth=.5, position="dodge")
ggplotly(p)
Click to copy
Add Facet
library(plotly)
df <- data.frame (type=rep(1:2, each=1000), subtype=rep(c("a","b"), each=500), value=rnorm(4000, 0,1))
library(plyr)
df.text<-ddply(df,.(type,subtype),summarise,mean.value=mean(value))
p <- ggplot(df, aes(x=value, fill=subtype)) +
geom_histogram(position="identity", alpha=0.4)+
facet_grid(. ~ type)
ggplotly(p)
Click to copy
Probability & Density
library(plotly)
df <- data.frame(x = rnorm(1000))
p <- ggplot(df, aes(x=x)) +
geom_histogram(aes(y = ..density..), binwidth=density(df$x)$bw) +
geom_density(fill="red", alpha = 0.2)
ggplotly(p)
Click to copy
What About Dash?
Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Learn about how to install Dash for R at https://dashr.plot.ly/installation.
Everywhere in this page that you see fig
, you can display the same figure in a Dash for R application by passing it to the figure
argument of the Graph
component from the built-in dashCoreComponents
package like this:
library(plotly)
fig <- plot_ly()
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... )
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
app <- Dash$new()
app$layout(
htmlDiv(
list(
dccGraph(figure=fig)
)
)
)
app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)
Click to copy