Multiple Y Axes Plot with Plotly

Introduction

This post briefly describe how to produce a multiple axes plot in R using plotly. Happy reading!!!

Generate the Data

countM <-rpois(n = 26, lambda = 10)
countF <-rpois(n = 26, lambda = 10)
rateM <- countM/1000
rateF <- countF/1000
age <- LETTERS[seq( from = 1, to = 26 )]
data <- data.frame(countM, countF, rateM, rateF, age)

Load the packages

require(tidyverse)
require(ggplot2)
require(plotly)

Create the Multiple Y Axes

#create
ay <- list(
  tickfont = list(color = "red"),
  overlaying = "y",
  side = "right",
  title = "Rate"
)

l <- list(
  font = list(
    family = "sans-serif",
    size = 12,
    color = "#000"),
  bgcolor = "#E2E2E2",
  bordercolor = "#FFFFFF",
  borderwidth = 2,
  orientation= "h", x = 1.05, y = 1)


p <- plot_ly(data, x = ~age, y = ~countM, type = 'bar', name = 'Male') %>%
  add_trace(y = ~countF, name = 'female') %>%
  add_lines(x=~age, y=~rateM, name = "rate of Male", yaxis = "y2") %>%
  add_lines(x=~age, y=~rateF, name = "rate of Female", yaxis = "y2") %>%
  layout(title = 'Age and Sex distribution', 
         yaxis = list(title = 'count'), 
         xaxis= list(title="Age"), 
         yaxis2 = ay, 
         barmode = 'group',
         bargap = 0.15, legend= l)

p

You can create a link to your chart

# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
# chart_link = api_create(p, filename="multiple-y-axes")
# chart_link
Lecturer in Statistics

My research interests include Geospatial epidemiology, Spatio-temporal statistics, Disease mapping and Predictive modelling