簡體   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