我想显示饼图很多年,用户可以点击其中一个切片来选择一个类别来绘制条形图,以便更容易地看到年度变化那个类别。单击切片将有效地执行selectInput在以下脚本中执行的操作:
library(rCharts)
library(shiny)
Year1 <- c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5)
Year2 <- c(1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,5,5,5,5,5)
Year3 <- c(1,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,5,5,5)
data <- data.frame(Year1,Year2,Year3)
shinyApp(
ui = fluidPage(
showOutput("p1", lib = "nvd3"),
showOutput("p2", lib = "nvd3"),
showOutput("p3", lib = "nvd3"),
selectInput("selected","Select group to graph:",
choices = c(1:5),
multiple = FALSE,
selected = 1),
showOutput("bar", lib = "highcharts")
),
server = function(input, output){
output$p1 <- renderChart2({
nPlot(~ Year1, data = data, type = 'pieChart')
})
output$p2 <- renderChart2({
nPlot(~ Year2, data = data, type = 'pieChart')
})
output$p3 <- renderChart2({
nPlot(~ Year3, data = data, type = 'pieChart')
})
data2 <- reactive({
data.frame(Year1 = as.data.frame(table(data$Year1))[input$selected,2],
Year2 = as.data.frame(table(data$Year2))[input$selected,2],
Year3 = as.data.frame(table(data$Year3))[input$selected,2]
)
})
output$bar <- renderChart2({
a <- rCharts:::Highcharts$new()
a$chart(type = "column")
a$title(text = "Bar Chart")
a$xAxis(title = list(text = "Yearly Data"))
a$yAxis(title = list(text = "Count"))
a$data(data2())
a
})
}
)
非常感谢任何帮助。如果有更合适的话,我不反对使用其他软件包。
答案 0 :(得分:1)
从this启发,您可以添加自定义工具提示功能,在您点击饼图时添加点击事件:
tooltip_function="#! function(key, x, y, e ){
d3.selectAll('[class*=\"nv-slice\"]').on('click',function(){
Shiny.onInputChange('selected_cat',key)})
return '<h3>' + key + '</h3>' + '<p>'+ x +'</p>'
} !#"
Shiny.onInputChange
将selected_cat
绑定到key
的值,这是用户点击的饼图的名称。然后,您可以使用input$selected_cat
在server.R
中获取该值。
需要修改renderChart2
以添加工具提示功能(例如第一个):
output$p1 <- renderChart2({
n1 <- nPlot(~ Year1, data = data, type = 'pieChart')
n1$chart(tooltipContent = tooltip_function)
n1
})
data2
:
data2 <- reactive({
data.frame(Year1 = as.data.frame(table(data$Year1))[input$selected_cat,2],
Year2 = as.data.frame(table(data$Year2))[input$selected_cat,2],
Year3 = as.data.frame(table(data$Year3))[input$selected_cat,2]
)
})