繁体   English   中英

如何在 Plotly 中从另一个 Z6A8064B5DF4794555500553C47C55057DZ 中提取的列名中提取 plot a

[英]How to plot a in Plotly from a column name extracted from another dataframe in R

我在下面给出了两个示例数据框

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 制成)并将提取的值用于 plot 中的条形图 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 = ""))
})

我没有得到 output。 我尝试了一些类似 get(col_word) 的方法,但是它不起作用。

结果col_word是一个字符值(例如,“bat”)。

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

您可以使用aes_stringggplot中解决这个问题。 但是,在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 = ""))
})
```

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM