【发布时间】:2021-01-09 15:55:03
【问题描述】:
按照to this question 的答案之一,我想在 plotly 上创建一个多 y 轴图。
我创建了一个闪亮的示例,我希望用户:
- 从 selectInput 中选择要位于 Y 轴上的变量并将变量名称传递给相应的 y 轴
- 根据所选变量的数量和名称更改 Y 轴的顺序和数量。
这是我手动选择 Y 轴数据的代码:
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)
【问题讨论】:
标签: r shiny plotly r-plotly shiny-reactivity