Here’s a step-by-step tutorial for Day 1 to get you started
with plotly in R. This guide
will walk you through the installation process and teach you how to create
basic interactive plots like scatter, bar, and line charts.
Step 1: Install and Load plotly
1. Open RStudio (or any R environment): Make sure
you have an R environment ready to work with.
2. Install plotly:
If you haven’t installed plotly
yet, use the following code:
install.packages("plotly")
3. Load plotly:
Load the library so that you can use it in your session.
library(plotly)
Step 2: Create Basic Interactive Plots
A. Scatter Plot
1. Create Sample Data: For the scatter plot, let’s create a simple dataset to plot.
# Sample datax <- c(1, 2, 3, 4, 5)y <- c(10, 15, 13, 17, 20)
2. Create a Scatter Plot with plot_ly(): Use plot_ly() to create an interactive
scatter plot.
scatter_plot <- plot_ly(x = ~x, y = ~y, type = 'scatter', mode = 'markers')scatter_plot
- Explanation:
x = ~xandy = ~y: Define the x and y coordinates for the points.type = 'scatter': Specifies a scatter plot.mode = 'markers': Displays only markers (you can also try'lines+markers').
B. Bar Chart
1. Create Sample Data for a Bar Chart:
categories <- c("A", "B", "C", "D")values <- c(20, 14, 23, 17)
2. Create a Bar Chart:
bar_chart <- plot_ly(x = ~categories, y = ~values, type = 'bar')bar_chart
- Explanation:
x = ~categories: Defines the x-axis labels.y = ~values: Defines the values for each bar.type = 'bar': Specifies a bar chart.
C. Line Chart
1. Create Data for a Line Chart:
time <- c(1, 2, 3, 4, 5)values <- c(3, 7, 9, 6, 10)
2. Create a Line Chart:
line_chart <- plot_ly(x = ~time, y = ~values, type = 'scatter', mode = 'lines')line_chart
- Explanation:
type = 'scatter'withmode = 'lines': This combination creates a line plot.x = ~timeandy = ~values: Define the x and y coordinates for the line.
Step 3: Customize Your Plots
You can customize colors, add titles, and adjust axis labels for each plot.
1. Add Titles and Labels:
# Scatter Plot with Labelsscatter_plot <- scatter_plot %>% layout(title = "Interactive Scatter Plot", xaxis = list(title = "X Axis"), yaxis = list(title = "Y Axis")) # Bar Chart with Labelsbar_chart <- bar_chart %>% layout(title = "Interactive Bar Chart", xaxis = list(title = "Categories"), yaxis = list(title = "Values")) # Line Chart with Labelsline_chart <- line_chart %>% layout(title = "Interactive Line Chart", xaxis = list(title = "Time"), yaxis = list(title = "Values"))
2. View Customized Plots: Display each plot with the customized labels.
scatter_plotbar_chartline_chart
Step 4: Explore Interactivity
Hover over the data points on each plot to see interactive information, and
try zooming and panning. plotly
provides built-in interactivity, including tooltips and customizable actions.




