✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.

# geom_histogram in ggplot2

How to make a histogram in ggplot2. Examples and tutorials for plotting histograms with geom_histogram, geom_density and stat_density.

New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

### 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)

fig <- ggplotly(p)

fig


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")

fig <- ggplotly(p)

fig


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)

fig <- ggplotly(p)

fig


### 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)

fig <- ggplotly(p)

fig


### 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)
)
)
)