Following the one of the answers to this question I want to create a multiple y axis graph on plotly .
I have created a shiny example and I would like the user to:
- choose the variable to be on Y axis from a selectInput and pass variable name to the corresponding y axis
- change the order and number of Y axes depending on the number and names of variable selected.
Here is my code with manually selected data for Y axis:
library(shiny)
library(plotly)
data <- data.frame (
Year = c(2010, 2011, 2012, 2013, 2014),
Weight = c(56, 60, 67, 65, 70),
Height = c(160, 165, 168, 171, 173),
BMI = c(21.9, 22.0, 23.7, 22.2, 23.4),
Girth = c(32, 33, 34, 34, 33)
)
ui <- fluidPage(
selectInput("variable", "Variable:",
c("Weight(Kg)","Height(cm)","BMI(kg/m2)", "Girth(cm)"),
multiple=TRUE),
plotlyOutput(outputId = "Graph") )
server <- function(input, output) {
output$Graph <-renderPlotly({
plot_ly(data, x = ~data$Year, type = 'scatter', mode = 'lines') %>%
add_lines(y = ~data[, 2], name='Weight(Kg)', line = list(color = "red")) %>%
add_lines(y = ~data[, 3], name='Height(cm)', yaxis='y2', line = list(color = "orange")) %>%
add_lines(y = ~data[, 4], name='BMI(kg/m2)', yaxis='y3', line = list(color = "darkgreen")) %>%
layout(
xaxis = list(title = "time", domain = c(0.5,1)),
yaxis = list(title = 'Weight(Kg)', side = "left", color = "red", position = 0,
anchor = 'free'),
yaxis2 = list(title = 'Height(cm)', side = "left", color = "orange",
overlaying = "y", anchor = 'free', position = 0.1),
yaxis3 = list(title = 'BMI(kg/m2)', side = "left",
overlaying = "y", anchor = 'free', color = "darkgreen", position = 0.2),
yaxis4 = list(title = 'Y-axis 4', side = "left",
overlaying = "y", anchor = 'free', color = "purple", position = 0.3),
yaxis5 = list(title = 'Y-axis 5',side = "left",
overlaying = "y", anchor = 'free', color = "brown", position = 0.4),
showlegend = T
)
})
}
shinyApp(server = server, ui = ui)