首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从点击中获取x类别

如何从点击中获取x类别
EN

Stack Overflow用户
提问于 2021-10-10 22:41:06
回答 1查看 56关注 0票数 1

如何通过在shiny中单击从条形图中获取类别(x轴信息)。请看下面的应用程序。我希望当用户单击绘图中的某个条形图时,output$cut会显示cut类型。

代码语言:javascript
运行
复制
library(shiny)
library(ggplot2)
library(dplyr)

ui <- fluidPage(
  plotOutput('diamonds', click = "click"),
  textOutput('cut')
)

server <- function(input, output, session) {
  output$diamonds <- renderPlot({
    diamonds %>% 
      ggplot() +
      geom_bar(aes(cut))
  })
  
  output$cut <- renderText({
    req(input$click)
    
    # This isn't meaningful
    x <- round(input$click$x, 2)
    y <- round(input$click$y, 2)
    cat("[", x, ", ", y, "]", sep = "")
    
    # and this doesn't work either
    # nearPoints(diamonds, input$click, xvar = "cut")
  })
}

shinyApp(ui, server)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-10 23:12:31

您从input$click$x获得的x值对应于所单击的因子。需要将其四舍五入为整数,并可用于获取因子名称。

因子名称可用于筛选diamonds数据集。

代码语言:javascript
运行
复制
x <- round(input$click$x) ## this will return a whole number corresponding to the factor that was clicked on.

##filter for the selected cut by using levels to get the name of the factor.
selected_cut <- diamonds %>% filter(cut == levels(diamonds$cut)[x])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69519497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档