Building a Butterfly plot in R

Adarsha Regmi
2 min readMay 31, 2022

--

I have make use of plotly package for this task.

Butterfly plot

Our first thing to do is have required packages installed in the system. The things we require include Plotly (obs.), dplyr, tidyr (for calculation purposes only.)

library(plotly)
library(dplyr)
library(tidyr)

Lets first create a dataframe to test our things.

dat <- data.frame(
a = c("A", "B", "C"),
b = c(1,2,3),
b1 = c(8,9,10),
c = c(1,2,3),
c1 = c(8,9,10))

Now that we have our data frame ready just have a bar plot that has three attributes to show.

b <- dat %>% plot_ly(x=~b, y=~a, type="bar", orientation="h") %>%
add_trace(x=~b1, type="bar")
running above command we have

similarly for another side plot

a <- dat %>% plot_ly(x=~c, y=~a, type="bar", orientation="h") %>%
add_trace(x=~c1, type="bar")

Now lets join this tables,

subplot(a, b)

We have joined the plots,but first needs to rotated. so lets change the xrange value for first plot.

a <- dat %>% plot_ly(x=~c, y=~a, type="bar", orientation="h") %>%
add_trace(x=~c1, type="bar") %>%
layout(xaxis=list(range=c(15,0))

We have added layout layer at the last layer.

so the plot is reversed now.

The plot can be customised as per your need. But basic things are included now. We can add barmode as ‘group’, ‘overlay’, ‘stack’ ,etc.

# stacked mode

stacked bar mode example

--

--

No responses yet