I have two sample dataframes given below
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)
Using the code below I want to extract the column name from drop down menu (made from df1) and use the extracted value to plot the bar graph in plotly using extracted value as column in df2. I am doing this is 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 = ""))
})
I get no output. I have tried a couple of things like get(col_word) however, it does not work.
The result col_word
is a character value (eg, "bat").
For plot_ly
, you need a data frame column, or list or vector, not a character string.
You can get around this in ggplot
using aes_string
. However, in plotly
you need an alternative --- you can try:
plot_ly(df2, x = ~class, y = ~get(col_word), type = 'bar') %>%
layout(yaxis = list(title = 'Count'), xaxis = list(title = ""))
Or:
plot_ly(df2, x = ~class, y = as.formula(paste0('~', col_word)), type = 'bar') %>%
layout(yaxis = list(title = 'Count'), xaxis = list(title = ""))
Edit : Make sure to also use renderPlotly
(note the 'ly' at the end).
Here is a full working example in R Markdown with 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 = ""))
})
```
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.