Filled Area in ggplot2

How to make Filled Area 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 stacked area plot

The data frame used as input to build a stacked area chart requires 3 columns: * x: numeric variable used for the X axis, often it is a time. * y: numeric variable used for the Y axis. What are we looking at? * group: one shape will be done per group.

The chart is built using the geom_area() function.

library(plotly)
library(ggplot2)
library(dplyr)

time <- as.numeric(rep(seq(1,7),each=7))
value <- runif(49, 10, 100)
group <- rep(LETTERS[1:7],times=7)
data <- data.frame(time, value, group)

p <- ggplot(data, aes(x=time, y=value, fill=group)) + 
    geom_area()

ggplotly(p)

Control stacking order

The gallery offers a post dedicated to reordering with ggplot2. This step can be tricky but the code below shows how to:

  • give a specific order with the factor() function.
  • order alphabetically using sort()
  • order following values at a specific data
library(plotly)
library(ggplot2)
library(dplyr)

time <- as.numeric(rep(seq(1,7),each=7))
value <- runif(49, 10, 100)
group <- rep(LETTERS[1:7],times=7)
data <- data.frame(time, value, group)

data$group <- factor(data$group , levels=c("B", "A", "D", "E", "G", "F", "C") )

p <- ggplot(data, aes(x=time, y=value, fill=group)) + 
    geom_area()

ggplotly(p)

Proportional stack

In a proportional stacked area graph, the sum of each year is always equal to hundred and value of each group is represented through percentages.

library(plotly)
library(ggplot2)
library(dplyr)
data <- data  %>%
  group_by(time, group) %>%
  summarise(n = sum(value)) %>%
  mutate(percentage = n / sum(n))

p <- ggplot(data, aes(x=time, y=percentage, fill=group)) + 
    geom_area(alpha=0.6 , size=1, colour="black")

ggplotly(p)

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)