如何根据从R中的另一个数据帧中提取的列名在绘图中绘制

如何根据从R中的另一个数据帧中提取的列名在绘图中绘制,r,dplyr,plotly,R,Dplyr,Plotly,下面给出了两个示例数据帧 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

下面给出了两个示例数据帧

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生成的下拉菜单中提取列名,并使用提取的值以plotly方式绘制条形图,使用提取的值作为df2中的列。我在做这个是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 = ""))
})

我没有输出。我尝试过一些方法,比如getcol\u-word,但是它不起作用。

结果col\u-word是一个字符值,例如bat

对于plot_êly,您需要数据帧列、列表或向量,而不是字符串

您可以使用aes_字符串在ggplot中绕过此问题。但是,在plotly中,您需要一个替代方案,您可以尝试:

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

编辑:确保也使用renderply,并在末尾注意“ly”

以下是R Markdown中一个完整的工作示例:


df2中没有名为category的列,因此不会打印。尝试在绘图中更改x=~类call@e.matt. 谢谢你的回复。我试着改变x=~类。它仍然不起作用。我尝试了你的两个建议。然而,什么也没有出现。我看不到绘图。还要确保使用renderply,并在结尾处注明“ly”。有关工作示例,请参见编辑的答案。
plot_ly(df2, x = ~class, y = as.formula(paste0('~', col_word)), type = 'bar') %>%
  layout(yaxis = list(title = 'Count'), xaxis = list(title = ""))
---
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 = ""))
})
```