Interactive bar chart that updates in real-time using a combination of javascript, html, and

Current Situation: I am currently in the process of iterating through a machine learning model and dynamically updating my "divs" as text labels. My goal is to transform these values into individual bars that visually represent the values instead of just displaying them as text.

Example In Action: Here's an example that illustrates what I'm working on. It's worth noting that the real code includes a function called predict() that continuously updates the values of the labels. The ultimate objective is to update the value of each bar within this function. Any assistance in converting this into a bar chart would be greatly appreciated.

let labelContainer = document.getElementById("label-container");
let maxPredictions = 8;
// this object is being updated constantly
let prediction = [
    {
        "className": "Prediction 1",
        "probability": .1
    },
    {
        "className": "Prediction 2",
        "probability": .2
    },
    {
        "className": "Prediction 3",
        "probability": .05
    },
    {
        "className": "Prediction 4",
        "probability": .25
    },
    {
        "className": "Prediction 5",
        "probability": .1
    },
    {
        "className": "Prediction 6",
        "probability": .20
    },
    {
        "className": "Prediction 7",
        "probability": .05
    },
    {
        "className": "Prediction 8",
        "probability": .05
    }
];

function init() {
for (let i = 0; i < maxPredictions; i++) { // and class labels
        labelContainer.appendChild(document.createElement("div"));
      }
}
// this function is constantly being called
function predict() {
for (let i = 0; i < maxPredictions; i++) {
        const classPrediction =
          prediction[i].className + ": " + prediction[i].probability.toFixed(2);
        
        labelContainer.childNodes[i].innerHTML = classPrediction;
      }
}

init();
predict();


      
      
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
</head>
<body>
  <div id="label-container"></div>
</body>

Desired Visual Outcome:

Answer №1

Here is a basic template that you can use as a starting point.

I increased the value * 100 for better visualization.

let labelContainer = document.getElementById("label-container");
let maxPredictions = 8;
// This object is continuously updated
let prediction = [
    {
        "className": "Prediction 1",
        "probability": .1
    },
    {
        "className": "Prediction 2",
        "probability": .2
    },
    {
        "className": "Prediction 3",
        "probability": .05
    },
    {
        "className": "Prediction 4",
        "probability": .25
    },
    {
        "className": "Prediction 5",
        "probability": .1
    },
    {
        "className": "Prediction 6",
        "probability": .20
    },
    {
        "className": "Prediction 7",
        "probability": .05
    },
    {
        "className": "Prediction 8",
        "probability": .05
    }
];

function init() {
for (let i = 0; i < maxPredictions; i++) { // and class labels
      let el = document.createElement("div")
      el.className = 'prediction-bar'
        labelContainer.appendChild(el);
      }
}
// This function is called continuously
function predict() {
for (let i = 0; i < maxPredictions; i++) {
        const classPrediction =
          prediction[i].className + ": " + prediction[i].probability.toFixed(2);
        
        labelContainer.childNodes[i].innerHTML =  `
          <div class="name-progress">${classPrediction}</div>
            <div class="progress">
              <div class="inner-progress" style="width:${prediction[i].probability.toFixed(2)*100}%">${prediction[i].probability.toFixed(2)*100}%
             </div>
          </div>`;
      }
}

init();
predict();
#label-container > div {
  margin: 0.5em;
}

.prediction-bar {
  display: flex;
}

.progress {
    flex: 1;
    background: #000;
    position: relative;
    border-radius: 0.25rem;
    padding: 0.25rem;
    position: relative;
    overflow: hidden;
    color: #fff;
    margin-left: 1rem;
}

.inner-progress {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  background: red;
  text-align: right;
}
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
</head>
<body>
  <div id="label-container"></div>
</body>

Answer №2

If you want to visualize your predictability bars, one way to do it is by referring to a resource I came across on CSS-tricks - Making Charts with CSS. Keep in mind that the snippet provided may not work here, so I recommend checking it out through the link above or testing it on codepen.io.

dl {
  display: flex;
  background-color: white;
  flex-direction: column;
  width: 100%;
  max-width: 700px;
  position: relative;
  padding: 20px;
}

dt {
  align-self: flex-start;
  width: 100%;
  font-weight: 700;
  display: block;
  text-align: center;
  font-size: 1.2em;
  font-weight: 700;
  margin-bottom: 20px;
  margin-left: 130px;
}

.text {
  font-weight: 600;
  display: flex;
  align-items: center;
  height: 40px;
  width: 130px;
  background-color: white;
  position: absolute;
  left: 0;
  justify-content: flex-end;
}

.percentage {
  font-size: .8em;
  line-height: 1;
  text-transform: uppercase;
  width: 100%;
  height: 40px;
  margin-left: 130px;
  background: repeating-linear-gradient(
  to right,
  #ddd,
  #ddd 1px,
  #fff 1px,
  #fff 5%
);
  
  &:after {
    content: "";
    display: block;
    background-color: #3d9970;
    width: 50px;
    margin-bottom: 10px;
    height: 90%;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    transition: background-color .3s ease;
    cursor: pointer;
  }
  &:hover,
  &:focus {
    &:after {
       background-color: #aaa; 
    }
  }
}

@for $i from 1 through 100 {
  .percentage-#{$i} {
    &:after {
      $value: ($i * 1%);
      width: $value;
    }
  }
}

html, body {
  height: 500px;
  font-family: "fira-sans-2",sans-serif;
  color: #333;
}
<dl>
  <dt>
    Browser market share June 2015
  </dt>
  <dd class="percentage percentage-11"><span class="text">IE 11: 11.33%</span></dd>
  <dd class="percentage percentage-49"><span class="text">Chrome: 49.77%</span></dd>
  <dd class="percentage percentage-16"><span class="text">Firefox: 16.09%</span></dd>
  <dd class="percentage percentage-5"><span class="text">Safari: 5.41%</span></dd>
  <dd class="percentage percentage-2"><span class="text">Opera: 1.62%</span></dd>
  <dd class="percentage percentage-2"><span class="text">Android 4.4: 2%</span></dd>
</dl>

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

Issues with Bootstrap form functionality

I found inspiration on http://getbootstrap.com and decided to enhance it by including a hidden input. The file result.php contains $_REQUEST. Only the hidden value is visible to me. <form class="form-horizontal" role="form" action="/requests/result.p ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

Tips for eliminating the ripple effect when clicking on a q-list item

I have managed to create a sleek sidebar with a curved edge that seamlessly integrates into the body of the page. However, I am struggling to remove the semi-transparent ripple effect that appears when clicking on a list item. The current effect clashes ...

Implementing Sass mixin transition to specifically add transition-delay - a comprehensive guide

As I continue to enhance my front-end development skills and practice Sass to optimize my CSS code, I encountered a roadblock. After exploring resources and tutorials online, I created a global mixin in Sass named 'transition'. Here is the code: ...

What's the best way to target an input that's appearing as it slides in from the edge of the screen?

My webpage has an element called #cols that is three times wider than the <body>. This element contains three columns, each exactly as wide as the <body>. When a button is clicked, the #cols element slides over by the width of one column while ...

The confirm() function shows up before the background on a blank layout

I'm facing an issue where whenever my confirm() function pops up, the alert box displays correctly but then the background turns blank. I've tried various solutions like moving the entire if statement to the bottom of the page or at the end of th ...

How can I incorporate multiple states into a conditional statement in ReactJS?

Is there a more efficient way to achieve this task? I'm struggling to come up with a cleaner solution as the current approach looks messy. I need to check multiple states in an if statement and the only method I can think of right now is the one prese ...

What is the best way to create a four-column layout using only CSS when the widths of the columns will vary?

I am looking to create a four-column layout using only CSS, where the width of the columns will adjust responsively. To better understand my issue, take a look at the code snippet below: .row { width: 100%; display: table; } .col { display: table ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...

"Enhance your website design with a navbar that seamlessly blends with the background color

Question 1: I have a requirement for my navbar to affix overlay on top of the background color and image of the div (top-banner). Currently, when I scroll down, the background color overlays my navbar affix instead. How can I ensure that my navbar sta ...

Could a complex, intricate clipping path be created using CSS 3?

Here is an example: Can this be achieved using only CSS? I wish to create two divs: A circle without any background or border. A div with a background. I aim to have point 1 clip the background from point 2. This will allow me to rotate the backgroun ...

Selecting the appropriate technology or library for incorporating user-defined text along a designated path within established areas

I am currently developing an admin dashboard with CodeIgniter 2 that allows the admin to upload custom images, particularly ones with blank spaces for text overlay. The goal is to enable regular users to add their desired text in specific areas defined by ...

Identifying and recording duplicate values within an array using object transformation in JavaScript

I currently have an array structured like this: uniqueCount = [a,a,b,c,d,a,a]; I'm trying to figure out how many occurrences of each element (a, b, c) are in the array. I'd like to display the results in the form of an array of objects: [{key ...

Displaying a list of JSON data in HTML using Angular.js is a breeze

I am attempting to create an HTML list displaying the id fields of game objects from a json file. However, it is not appearing in my user interface. I am unsure why it is not rendering properly. ---core.js--- var gameapp = angular.module('gameapp&ap ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

What is the best way to adjust the screen to display the toggle element when it is opened?

Here is the code I'm currently using to create a toggle button that shows or hides extra content when clicked: $(".toggle .button").click(function() { $(this).next().slideToggle('fast'); }); The issue I am encountering is that if t ...

Animate with jQuery to swap the positions of two floating divs

Hello, I recently made some updates to the code by adding 2 divs of different sizes. I am trying to achieve a switching animation using CSS floats for these divs. If you'd like to take a look at the current code, please visit - http://jsfiddle.net/jz ...

Mastering the art of effectively capturing and incorporating error data

Is there a way to retain and add information to an Error object in typescript/javascript without losing the existing details? Currently, I handle it like this: try { // code that may throw an error } catch (e) { throw new Error(`Error while process ...

Issues with CORS on PUT and POST requests in AngularJS and Node.js are preventing successful communication between the two

I'm encountering a CORS issue with my application. My tech stack consists of Node.js using Express 4 and AngularJS Despite attempting various solutions, I continue to receive the following error for all POST/PUT requests: No 'Access-Control-Al ...