Assigning an object to a field within an array using Vega-lite

I am currently working on an interactive data dashboard with a dataset stored in an array of objects. I want to enhance the functionality by displaying data from one object at a time instead of all objects collectively, which is already functioning well. To test this new feature, I have set up a basic array:

var test1 = [
  [{
    "name": "Piece One",
    "amount": 5
  }, {
    "name": "Piece Two",
    "amount": 5
  }, {
    "name": "Piece Three",
    "amount": 5
  }],
  [{
    "name": "Piece One",
    "amount": 1
  }, {
    "name": "Piece Two",
    "amount": 1
  }, {
    "name": "Piece Three",
    "amount": 5
  }]
];

Alongside this, there's Vega-lite javascript included:

var pieCreate = {
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "title": "A pie chart",
  "description": "A simple pie chart with embedded data.",
  "width": "container",
  "height": "container",
  "data": {"values": test1[0]},
  "mark": "arc",
  "encoding": {
    "theta": {
      "field": "amount",
      "type": "quantitative"
    },
    "color": {
      "field": "name",
      "type": "nominal",
      "legend": null
    }
  }
};

The current setup works fine, but now I aim to allow users to choose a specific object to display. Each object represents data from different schools, and I want users to pick a school through a dropdown menu in the dashboard. Initially, I considered setting up a signal within the

"data": {"values":
section to alter the array index, but after numerous attempts, it seems like a dead end. Signals should theoretically be able to modify
"field": "amount"
and
"field": "name"
, however, my various attempts using [0].amount syntax for direct access hasn't yielded success. If I can find a way to directly reference the object in the "field": part, then I believe I could progress with a signal and html form solution, although doubts linger about being on the correct track.

I also tried following the guidelines provided in the vega-lite documentation here: . However, the concept presented there appears more complex than what I need, and due to limitations in my javascript knowledge, I struggle to simplify it for practical use. Are there any suggestions or ideas to achieve this goal using the discussed methods or perhaps a more efficient approach?

Answer №1

To modify the data, utilize the functionalities provided by the Vega API. Incorporate a change event upon selection and use specific conditions to switch between different datasets using these APIs. You can refer to the code snippet below or check out this JSFiddle example:

var test1 = [
  [{
    "name": "Piece One",
    "amount": 5
  }, {
    "name": "Piece Two",
    "amount": 5
  }, {
    "name": "Piece Three",
    "amount": 5
  }],
  [{
    "name": "Piece One",
    "amount": 1
  }, {
    "name": "Piece Two",
    "amount": 1
  }, {
    "name": "Piece Three",
    "amount": 5
  }]
];

var yourVlSpec = {
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "title": "A pie chart",
  "description": "A simple pie chart with embedded data.",
  "width": "350",
  "height": "400",
  "data": {
    "values": test1[0]
  },
  "mark": "arc",
  "encoding": {
    "theta": {
      "field": "amount",
      "type": "quantitative"
    },
    "color": {
      "field": "name",
      "type": "nominal",
      "legend": null
    }
  }
}
var view;
vegaEmbed("#vis", yourVlSpec).then(res => {
  view = res.view;
});

function handleChange(a, b) {
  var selectValue = document.getElementById("myselect").value;
  if (selectValue == 'A') {
    view.data('source_0', test1[0]);
  } else {
    view.data('source_0', test1[1]);
  }
  view.runAsync();
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a3c2f2d2b0a7f64787a644f6c0d177b60006660eb060a02">[email protected]</a>/build/vega.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43305b5d594e41567c41417876406a514954">[email protected]</a>/build/vega-lite.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="621a05000768030e0c0222706951020f02155cc47788037c0009">[email protected]</a>/build/vega-embed.min.js"></script>

<select id="myselect" style="width:100px;" onchange="handleChange()">
  <option>A</option>
  <option>B</option>
</select>
<br>
<div id="vis"></div>

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 design an HTML page so that it changes its title daily?

I have a goal to change the site's title every day, but I am not an experienced programmer. I know that this can be done using JavaScript. I came across this idea: setInterval(function() { //change title //document.title = "Some new title"; ...

How can I use JavaScript to retrieve information from a different webpage?

I am trying to extract data from another webpage using JavaScript, jQuery, or Ajax without using PHP. I came across a helpful example on Stack Overflow (link here). However, when I implement these codes in my index.html file, it doesn't seem to work. ...

Tips for extracting HTML tags directly from JSON data

In my dataset, I have a JSON illustration [{ "Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n< ...

Troubleshooting Issue: Unable to Retrieve Loaded Record in Ember.js

I am facing an issue with accessing properties to change the header of my RESTAdapter after loading the user. Do you have any ideas why that might be happening? The code snippet in question is as follows: var user = ''; App.MainRoute = Ember.R ...

Dispose of jQuery instance when it is no longer required

Encountered an issue with jQuery: There are multiple div containers on a page with the class "stackgo" and different data attributes. For example: <div class=\"stackgo\" data-an=\"HEY\" data-ms=\"HO\" data-me=\"HM&bso ...

What is the process of invoking Link manually in React-router?

I am working on a component that is passed a <Link/> object from react-router as a prop. When the user clicks on a 'next' button within this component, I need to manually trigger the <Link/> object. Currently, I am using refs to acce ...

Removing the root component in ReactJS can be done on specific pages by implementing

Is there a way to remove the <header/> and <footer/> components from my signup.js and signin.js pages without altering the root index.js file? Presently, the root index.js file looks like this: class Template extends React.Component { render( ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Navigating with buttons in the Material UI Drawer

I have implemented a Material UI drawer with some modifications. The original code used buttons, but now I want to navigate to a new page when a button is clicked. For example, clicking on the 'INBOX' button should take me to a page '/new&ap ...

Identify and forward to the mobile-friendly version of the site

I am currently working on a website that requires separate files for mobile view as the html layout poses challenges in making it responsive. My goal is to find code that can detect if the user is accessing the site from a mobile device, and automatically ...

The behavior of having two submit buttons within the $document.ready(function) in Jquery

In my code, I have implemented the behavior of two buttons, button1 and button2, within a $(document).ready(function). Whenever either button is clicked, an alert() function should be triggered. However, it seems that only button2 is functioning properly w ...

Looking for a specific integer within an array of integers stored in a json format

After sorting my json array of integers, I am now looking to efficiently find a specific integer element within the json array. The size of the json array can vary, but it exclusively consists of integers. What would be the most effective approach to per ...

Real-time webpage featuring dynamically updating text sourced from a file

After spending 5 hours attempting this on my own, I've decided to reach out for help. I am in need of creating a page that will automatically update itself and display the content of a file when it changes. For example, let's say we have a file ...

The issue of 'MessageChannel not defined' arises specifically on web pages that have implemented reCaptcha v2

I am currently working on scraping some websites that have implemented reCAPTCHA, but I keep encountering an error when loading the page's source: (node:15536) UnhandledPromiseRejectionWarning: ReferenceError: MessageChannel is not defined. Despite a ...

Modifying the position of an HTML element within its parent tag using document.createElement

As I dive into learning Javascript, I've come across document.createElement. This method allows me to create an HTML tag and insert it into an existing HTML parent element. However, I have a specific question in mind: Is it possible to choose the exac ...

Combining an array of hashes that share a common key

Looking to merge values of certain fields in an array of hashes with custom separators? Here are two sample hashes from the array, but there could be more following the same sequence. { "details": [ { "place": "abc", "group": 3, "year": 2006, "id" ...

Send various data to the delete button using an AJAX request

I am encountering an issue where I am trying to pass 2 variables in the delete button, but for some reason, only one variable is being passed. Here is the DELETE icon code snippet. <a class="delete_employee" data-emp-id="<?php echo $row_dg["emp_id ...

Using target="_blank" does not seem to open a popup window in React

The issue is that the target="_blank" attribute is not working properly for the modal popup window. Instead, the link is opening in the same page and the popup is closing. <TermLink to="/legal/privacy-policy" target="_blank"> Privacy Pol ...

What could be causing the failure in Selenium's findElement(By.css("span:contains(string)") method?

I have been attempting to use selenium-webdriver to click on a specific element within a website, which happens to be plain text. However, when I use the following javascript code const spanElement = driver.findElement(By.css("span:contains('TEXT&apo ...

"Tricky HTML table layout challenge: Margins, paddings, and borders causing

Working with HTML <table cellpadding="0" cellspacing="0"> <tbody> <tr> <td> <img src="..."> </td> </tr> </tbody> </table> Applying CSS rules * { border: none; ...