Introduction This is the Week 3 assignment for the Developing Data Products course on Coursera. In this document, we create an interactive Plotly chart that responds to a user-controlled slider input.
Interactive Plot The following plot allows you to explore how the relationship between a car’s weight (wt) and miles per gallon (mpg) changes depending on the number of cylinders (cyl). Use the slider below to select how many cylinders you want to display.
data("mtcars")
steps <- lapply(sort(unique(mtcars$cyl)), function(cyl_val) {
list(
method = "restyle",
args = list(
"transforms[0].value", cyl_val
),
label = paste(cyl_val, "cylinders")
)
})
p <- plot_ly(
data = mtcars,
x = ~wt,
y = ~mpg,
type = 'scatter',
mode = 'markers',
color = ~as.factor(cyl),
colors = "Set1",
marker = list(size = 12),
text = ~paste("Car:", rownames(mtcars),
"MPG:", mpg,
"Weight:", wt,
"Cylinders:", cyl),
transforms = list(
list(
type = 'filter',
target = ~cyl,
operation = '=',
value = unique(mtcars$cyl)[1]
)
)
) %>%
layout(
title = "Interactive MPG vs Weight (Filter by Cylinders)",
xaxis = list(title = "Weight (1000 lbs)"),
yaxis = list(title = "Miles per Gallon"),
sliders = list(
list(
active = 0,
currentvalue = list(prefix = "Cylinders: "),
pad = list(t = 50),
steps = steps
)
)
)
p