在R的Rmd中从下拉框提取列名并用Plotly绘制df2柱状图遇无输出问题
问题修复方案
我帮你定位到了几个导致图表无输出的问题,修复后的完整可运行代码如下:
library(shiny) library(plotly) library(dplyr) df1 <- data.frame(words = c("bat", "vat","cat","mat"), count = c(3420, 2098, 2003, 1501), words_count = c("bat (3420)","vat (2098)", "cat (2003)", "mat (1501)"), stringsAsFactors = FALSE) df2 <- data.frame(class = c("A","B","C","D"), bat = c(10,0,30,20), vat = c(0,0,10,30), cat = c(20,30,0,10), mat = c(20,20,0,0), stringsAsFactors = FALSE) ui <- fluidPage( inputPanel( selectInput("words", label = "Choose the word", choices = df1$words_count, selected = df1$words_count[1], width = '100%') ), plotlyOutput("wordPlot") # 对应plotly图表的输出容器 ) server <- function(input, output) { output$wordPlot <- renderPlotly({ # 提取下拉框对应的目标列名 col_word <- df1 %>% filter(words_count == input$words) %>% pull(words) # 修复x轴列名,并动态引用目标列 plot_ly(df2, x = ~class, y = ~.[[col_word]], type = 'bar') %>% layout(yaxis = list(title = 'Count'), xaxis = list(title = "")) }) } shinyApp(ui, server)
具体问题解析:
- x轴列名错误:你的
df2中不存在category列,实际对应的列名是class,这会导致plotly找不到x轴数据来源。 - 动态列引用错误:plotly的
~语法是直接引用数据框的固定列名,当你用变量col_word存储动态列名时,需要用~.[[col_word]](或get(col_word))来获取对应列的值,而不是直接写~col_word。 - 渲染函数不匹配:plotly交互图表需要搭配
renderPlotly()和plotlyOutput()使用,renderPlot()是给基础静态绘图用的,用它无法正确渲染plotly图表。
内容的提问来源于stack exchange,提问作者varun khanna
相关产品推荐
相关产品推荐

