Utilizing selectInput to manipulate legends in a multibarChart with rCharts

Recently, I developed a straightforward application that incorporates a selectInput widget and a bar plot using rCharts. My goal is to generate the plot with a legend showcasing all three books, but only display information about the selected book by default. For instance, switching from Book1 to Book2 will initially show details about Book2, while the legend includes Book1 and Book3 (both deactivated by default) - allowing me to switch between them as needed. I suspect this issue lies within JavaScript, and despite my attempts to address it, no changes have occurred. Any suggestions on how to resolve this? Thank you!

library(shiny)
library(rCharts)

books <- c('Book1', 'Book2', 'Book3')
df <- data.frame(book = rep(books, each = 10), 
                 year = rep(2000:2009, 3),
                 sale = sample(100:1000, 30, replace = T))

ui <- shinyUI(
   fluidPage(
      HTML("
         <script>
            $( document ).ready(function() {
               if ( $(\"select#book div.selectize-dropdown div[data-value='Book1']\").hasClass('selected')) {
                  console.log('true');
                  $('#nvd3Plot .nv-legend g.nv-series').eq(1).addClass('disabled');
                  $('#nvd3Plot .nv-legend g.nv-series').eq(2).addClass('disabled');
               } else {
                  console.log('false');

               }
            }); 
         </script>"),

      selectInput('book', 'Select a book', choices = books, selected = 'Book1'),
      showOutput("nvd3Plot", "nvd3")
   )
)

server <- function(input, output, session) {
   output$nvd3Plot <- renderChart2({

      chartObject <- nPlot(sale ~ year, group = "book", data = df, type = "multiBarChart")
      chartObject$chart(
         showControls = FALSE
      )

      return(chartObject)
   })
}

shinyApp(ui, server)

Update

After stumbling upon this solution, I am uncertain how to implement it in R.

Answer №1

To control the series on an NVD3 horizontal multi-bar chart, you can utilize a custom message handler as discussed in this source.

In your ui.R, you can incorporate the following script:

tags$script('
        Shiny.addCustomMessageHandler("change_selected_book",
        function(book) {
          d3.select("g.nv-legendWrap").selectAll("g.nv-series.disabled")
          .each(function(d) {
            this.dispatchEvent(new Event("click"));
         });

          d3.select("g.nv-legendWrap").selectAll("g.nv-series").filter(
            function(d) { return d.key != book; })
        .each(function(d) {
            this.dispatchEvent(new Event("click"));
        });
        });
    ')

Within your server.R, add:

 observe({
    session$sendCustomMessage(type = "change_selected_book", input$book)
  })

This code automatically clicks on disabled series and then, apart from the selected book to disable, clicks on the legend of all other books to enable them.

An issue to note is that the selectInput element may display all three books initially until the user makes a selection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to specify the stream responseType for my client?

Is there a way to download a file from my express js app using AJAX instead of server-side handling? const response = await Axios({ method: 'GET', url: url, responseType: 'stream' }) Instead of piping the data directly to ...

Creating a basic voting system with Vue.js and Firebase: A step-by-step guide

Hello, and please forgive me if this question seems too basic, but I'm just starting out and feeling a bit overwhelmed. I'm attempting to allow a user to vote on and then remove their vote from an item posted by another user using the same butto ...

Using JavaScript to access the $_POST and $_FILES variables following an AJAX form submission

My current project involves using AJAX to submit a form and display a pre-selected image. When a user selects an image from their local drive, it triggers the "onchange" event for the file-type input field, which then initiates the AJAX routine. The proces ...

Providing both app and io as parameters to a module

Extracted from my server.js: const app = require('express')(); const server = require('http').createServer(app); const io = require("socket.io").listen(server); server.listen(port, function(){ console.log('Server listening at ...

Can the variable name be customized according to the input given?

My goal is to create multiple columns with randomized results independently of each other, based on user selection. I am not sure how many columns there will be, and I want the function to be repeatable as needed. While I know how to achieve this in PHP (u ...

Is it possible to dynamically load records in real time with the help of PHP and jQuery?

I developed a custom system using PHP that allows users to post status messages, similar to a microblog. The system utilizes a database table structured like this: posts_mst ------------------ post_id_pk post_title post_content date_added Initially, I su ...

One button for two forms to submit

I am looking to use two forms simultaneously. I believe this can be accomplished with the help of ajax. Form1 <form action="upload.php" method="post"> <label for="url">Enter URL:</label> <input type=" ...

Is it possible to attach a nested function to a parameter of the parent function in JavaScript?

Here's a query that might appear basic and straightforward. It could even be a repeated question, as I struggled to use the correct keywords in my search. The puzzle seems to lie in why this code snippet functions correctly: let rAMessage = 'Ri ...

Developing original data from an array in JavaScript

I am looking to create an API body for use in JavaScript fetch. The array contains around twenty items and I need to iterate through it using a loop. Here is an example of my array of objects: [ { name:"x",lname:"y" }, { name:" ...

"An error has occurred stating that the header is not defined in

It is a coding issue related to payment methods. The headers type is undefined in this scenario, and as a newcomer to typescript, pinpointing the exact error has been challenging. An error message is indicating an issue with the headers in the if conditio ...

Exploring every combination of columns and executing a function on each group in R: What's the best approach?

In my dataset called 'dt', I have a data table as shown below: set.seed(1) dt <- data.table(expand.grid(c("a","b"),1:2,1:2,c("M","N","O","P","Q"))) dt$perf <- rnorm(nrow(dt),0,.01) colnames(dt) <- c("ticker","par1","par2","row_n ...

Having trouble submitting a form in React JS

I'm facing an issue with my form where I am trying to print the data in console upon submission, but for some reason it's not working. The form is not submitting and I can't figure out why. Below is the code I have written. Any help would be ...

How many rows have been checked within an Angular framework?

I'm working on a project where I have a list of items with checkboxes, and I need to calculate the number of checked rows. Below is my directive code: <ul ng-repeat="person in list"> <li> <input type="checkbox" ng-model="se ...

Retrieving the value from a concealed checkbox

I have been searching everywhere, but I can't seem to find a solution to this particular issue. There is a hidden checkbox in my field that serves as an identifier for the type of item added dynamically. Here's how I've set it up: <inpu ...

Adding entire HTML content to a React component using dangerouslySetInnerHTML

I came across a helpful example demonstrating how to utilize the dangerouslySetInnerHTML() method. In the provided example, an anchor tag is being placed inside a div, but I am looking to insert complete HTML content instead. Upon receiving a response fr ...

Tips for updating the Google Map Key from a JAVASCRIPT script in DJANGO using a personalized variable

Is there a way to securely hide my Google Map API key in the JavaScript code? The key is dynamically generated from Django settings. I am uncertain about the proper implementation using JavaScript and src. settings.py GOOGLE_MAP = "XZZZZZZX" v ...

The field 'name' remains unchanged

I am in the process of developing a VS CODE THEME MAKER that generates a customized JSON file based on user input for colors. Below is all the necessary code: import download from 'downloadjs'; import React, { useState } from 'react'; i ...

Should the updater method be placed in the state or passed directly to the context?

Is it better to have this context setup like so: <MatchContext.Provider value={this.state.match}> Or should I structure it as follows in my state? match: { match: null, updateMatch: this.updateMatch }, Which approach is more eff ...

Get the latest version of Node Stream using Angular 2

I am currently working on generating a PDF file on the server side using node.js and then downloading it on the client side with Angular 4. It's similar to how Google Drive allows you to download files as PDFs. Here is an example of the Node JS code ...

Tips for removing a row from a table

I've been working on a responsive data table where each time I click an add button at the end of a row, a new row is added with the add button turning into a delete button. Below is the code I've implemented: The Table: <table id="invoice_ta ...