如何在Plotly中用R中从另一个数据框中提取的列名来绘制一个。

问题描述 投票:0回答:1

我有两个示例数据框,如下所示。

library(shiny)
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)

使用下面的代码,我想从下拉菜单中提取列名(从df1中提取),并使用提取的值作为df2中的列在plotly中绘制条形图。 我正在做的是Rmd。

inputPanel(
  selectInput("words", label = "Choose the word",
              choices = df1$words_count, 
              selected = df1$words_count[1], width = '100%')
  )

renderPlot({
# Extract the word from drop down
  col_word <- df1 %>% filter(words_count == input$words) %>% pull(words)

  plot_ly(df2, x = ~category, y = ~col_word, type = 'bar') %>%
    layout(yaxis = list(title = 'Count'), xaxis = list(title = ""))
})

我没有得到任何输出。我已经尝试了一些东西,比如get(col_word),但是,它没有工作。

r dplyr plotly
1个回答
1
投票

结果 col_word 是一个字符值(如 "bat")。

对于 plot_ly你需要一个数据框架列,或列表或向量,而不是一个字符串。

你可以在 ggplot 使用 aes_string. 然而,在 plotly 你需要另一种选择------你可以试试。

plot_ly(df2, x = ~class, y = ~get(col_word), type = 'bar') %>%
   layout(yaxis = list(title = 'Count'), xaxis = list(title = ""))

或者:

plot_ly(df2, x = ~class, y = as.formula(paste0('~', col_word)), type = 'bar') %>%
  layout(yaxis = list(title = 'Count'), xaxis = list(title = ""))

编辑...: 确保也使用 renderPlotly (注意结尾的'ly')。

下面是一个完整的R Markdown工作示例,其中包括 shiny:

---
title: "Test509"
author: "Ben"
date: "5/9/2020"
output: html_document
---

```{r setup, include=FALSE}
library(shiny)
library(plotly)
library(tidyverse)
```


```{r}
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)

inputPanel(
  selectInput("words", label = "Choose the word",
              choices = df1$words_count, 
              selected = df1$words_count[1], width = '100%')
)

renderPlotly({
  # Extract the word from drop down
  col_word <- df1 %>% 
    filter(words_count == input$words) %>% 
    pull(words)

  plot_ly(df2, x = ~class, y = ~get(col_word), type = 'bar') %>%
    layout(yaxis = list(title = 'Count'), xaxis = list(title = ""))
})
```
© www.soinside.com 2019 - 2024. All rights reserved.