0

I'm very new to R Markdown and Shiny, and I'm trying to make a simple interactive html document. I have two data frames that share the same row names (company names), and the rest are percentages based on different measures (each row adds up to 1). What I'd like to have is when people select a company, two bar plots will appear accordingly. I'm able to create a drop-down column but not sure how to add the two charts. Below are my codes:

  ---
  title: "Test"
  author: "Z"
  date: "March 30, 2018"
  output: html_document
  runtime: shiny
  ---

  ```{r}
  Names = c('A','B','C')
  Rev = c(-0.2,0.3,0.4)
  Mar = c(0.5,0.2,0.1)
  Mul = c(0.5,0.2,0.4)
  Lev = c(0.2,0.3,0.1)
  df1 = data.frame(Names,Rev,Mar,Mul,Lev)

  Sal = c(0.4,0.2,0.4)
  Ear = c(0.1,0.2,0.3)
  Pri = c(0.3,0.1,0.1)
  Dev = c(0.2,0.5,0.2)
  df2 = data.frame(Names,Sal,Ear,Pri,Dev)

  selectInput(inputId = 'Company', label = 'Choose a company',
        choices = Names)
  ```
T-T
  • 693
  • 1
  • 10
  • 24

1 Answers1

1

Here's one way to do it:

renderPlot({ ## wrap the plot prep and plot function in a reactive space
  data_to_plot <- unlist(df1[df1$Names == input$Company, 2: ncol(df1)]) # get data
  barplot(data_to_plot) # call the plot function
})

This works because shiny will only allow inputs to affect things in a reactive space (the curly brackets {}). Also, shiny inputs can be called using the input object.

Ryan Morton
  • 2,605
  • 1
  • 16
  • 19
  • I just tried on my dataset and encountered an issue which I didn't realize when putting together the sample - pie charts won't display negative values. I've updated my question and sample. I tried to change `pie` to `barplot` but it won't work `Error: non-numeric argument to binary operator`. Appreciate your help! – T-T Mar 30 '18 at 18:20
  • The plot functions take different arguments (of course you'll get an error), but the principles for shiny plots are the same... – Ryan Morton Mar 30 '18 at 18:26
  • Ha! Makes perfect sense. One last question: how can I show values on the top of the bars? I tried `text(x=data_to_plot, labels = as.character(data_to_plot))`. Values do show up but they are scattered and some of them only show half. – T-T Mar 30 '18 at 19:38
  • Here: https://stackoverflow.com/questions/12481430/how-to-display-the-frequency-at-the-top-of-each-factor-in-a-barplot-in-r – Ryan Morton Mar 30 '18 at 19:45