How to plot subplots using plotly in R?

This recipe helps you plot subplots using plotly in R

Recipe Objective

A line chart is a type of chart which showcases information as a sequence of data points also known as 'markers' which are connected by staright line. It is mainly used to plot the relationship or trend of a categorical variable with respect to a numerical variable. This type of chart could be one of the best example for subplotting. Any two graphs can be plotted side-by-side using subplot() function in Plotly. ​

In this recipe we are going to use Plotly package to plot the required line chart using Dual y axis. Plotly package provides an interface to the plotly javascript library allowing us to create interactive web-based graphics entrirely in R. Plots created by plotly works in multiple format such as: ​

  1. R Markdown Documents
  2. Shiny apps - deploying on the web
  3. Windows viewer

Plotly has been actively developed and supported by it's community. ​

This recipe demonstrates how to create two subplots (line charts) in R using plotly package ​

STEP 1: Loading required library and creating a dataframe

We will use an example of no of schools established in 2 states between 1970 and 2014

# Data manipulation package library(tidyverse) # plotly package for data visualisation install.packages("plotly") library(plotly) # years year = c('1970','1980', '1990', '2000', '2013', '2014') #no of schools in state1 corresponding to a particular year no_of_schools_state1 = c(15, 30, 60, 120, 240, 300) #no of schools in state2 corresponding to a particular year no_of_schools_state2 = c(55, 85, 200, 450, 600, 700) #creating a dataframe df = data.frame(year,no_of_schools_state1, no_of_schools_state2) df

year	no_of_schools_state1	no_of_schools_state2
1970	15			55
1980	30			85
1990	60			200
2000	120			450
2013	240			600
2014	300			700

STEP 2:Plotting 2 subplots (line charts) using Plotly

We use the plot_ly() and subplot() function to plot 2 line charts side-by-side.

Note:

  1. The %>% sign in the syntax earlier makes the code more readable and enables R to read further code without breaking it.
  2. We also use layout() function to give a title to the graph

# line chart 1 fig1 = plot_ly() %>% add_lines(data = df, x = ~year, y = ~no_of_schools_state1, name = "State1") #line chart 2 fig2 = plot_ly() %>% add_lines(data = df, x = ~year, y = ~no_of_schools_state2, name = "State2") # subplotting fig 1 and 2 fig = subplot(fig1, fig2) fig = fig %>% layout(title = 'Subplots using Plotly') embed_notebook(fig)

What Users are saying..

profile image

Ameeruddin Mohammed

ETL (Abintio) developer at IBM
linkedin profile url

I come from a background in Marketing and Analytics and when I developed an interest in Machine Learning algorithms, I did multiple in-class courses from reputed institutions though I got good... Read More

Relevant Projects

Personalized Medicine: Redefining Cancer Treatment
In this Personalized Medicine Machine Learning Project you will learn to classify genetic mutations on the basis of medical literature into 9 classes.

Avocado Machine Learning Project Python for Price Prediction
In this ML Project, you will use the Avocado dataset to build a machine learning model to predict the average price of avocado which is continuous in nature based on region and varieties of avocado.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Build Deep Autoencoders Model for Anomaly Detection in Python
In this deep learning project , you will build and deploy a deep autoencoders model using Flask.

Recommender System Machine Learning Project for Beginners-2
Recommender System Machine Learning Project for Beginners Part 2- Learn how to build a recommender system for market basket analysis using association rule mining.

Llama2 Project for MetaData Generation using FAISS and RAGs
In this LLM Llama2 Project, you will automate metadata generation using Llama2, RAGs, and AWS to reduce manual efforts.

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Digit Recognition using CNN for MNIST Dataset in Python
In this deep learning project, you will build a convolutional neural network using MNIST dataset for handwritten digit recognition.

MLOps AWS Project on Topic Modeling using Gunicorn Flask
In this project we will see the end-to-end machine learning development process to design, build and manage reproducible, testable, and evolvable machine learning models by using AWS

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.