# Building a Butterfly plot in R

I have make use of plotly package for this task.

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

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.

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