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:

https://i.sstatic.net/5lbuS.png

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 FullCalendar.js failing to consistently fire when used in conjunction with JS/Ajax/ColdFusion

Attempting to troubleshoot an issue with FullCalendar.js integration on an external page called "calendar_summary.cfm", which is part of a series of pages reloading on a main page. The data from calendar_summary.cfm is transferred into FullCalendar.js thro ...

Information submitted through an ajax request does not get saved in the $_POST array

After successfully executing an AJAX request using GET, I decided to try POST this time. However, when attempting to send data, a baffling error message appeared in the console - NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 'JavaScript component does ...

The fullcalendar is experiencing difficulties in showing the event

I am facing an issue with Fullcalendar where the events fetched by ajax are not showing up on the calendar. Even though the events are successfully passed and can be displayed in a pop-up, they do not render on the calendar. When manually setting the event ...

Unable to modify div style using a JS function

I am attempting to show different divs based on the button clicked, with all starting with a display style of "none" except for one default div called "atualizacoes". After clicking a button, all divs should be set to display="none", and then the specific ...

I am looking to transmit information from flask to React and dynamically generate HTML content based on it

index.py @app.route('/visuals', methods=["GET", "POST"]) def visuals(): global visclass return render_template('visframe.html', images=visclass.get_visuals()) visframe.html <div id='gallery'></div> { ...

Tips on generating a sample Mongoose Model with all null values

Imagine you are working with the following schema: var userSchema = new Schema({ name: String, schools: [{ level: String, name: String, timeInterval: { start: {type:Date,default:Date.now}, ...

VueJS: Unable to access the 'name' property as it is undefined"

I'm at a loss trying to figure out a solution for this issue. My current task involves editing a pub schedule using an edit form: pubs/UpdateProfile.vue <template> <confirm title="Edit Pub" ok="Save pub" :show="show" v-on:save="sa ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

What is the best way to integrate HTML templates into AngularJS?

I am currently working on developing an HTML fragment that will eventually function as an image slider. At this point, it only consists of a test div element: slider.html: <div>TEST</div> In order to incorporate this into my index.html, I hav ...

What are your thoughts on nesting an "li" tag within an "a" tag?

Consider this scenario: <ul> <a href="http://google.com"><li id="someId"></li></a> ... ... ... </ul> This is a solution I came up with to work around my current css styling. Now, I'm debating whether or not to ref ...

Gather image origins from a website, even if img tags are inserted through javascript or other methods during the page's rendering

I am looking to extract the URLs of all the images from a web page using C# and asp.net. Currently, I am utilizing: WebClient client = new WebClient(); string mainSource = client.DownloadString(URL); Afterwards, I am scanning the mainSource string for i ...

Optimizing the appearance of an unordered horizontal list in the most effective manner

When attempting to make lists horizontal and hide default bullets, is it necessary to apply {display:inline} and {float:left} to both the <li> tags or would just one of these properties suffice? <ul> <li><a href="#">First item< ...

Javascript encountering issues with recognizing 'self.function' within an onclick event

Recently, I have been working on enhancing a Javascript file that is part of a Twitter plugin. One of the key additions I made was implementing a filter function for this plugin. Here is a snippet of the script showcasing the relevant parts: ;(function ( ...

Unlinked from the main content, the Angular2 Material2 sidenav stands on its

I am in the process of implementing the material2 sidenav component. My goal is to have a standalone, full-height sidebar that smoothly slides in and out without any interference with the rest of the app layout caused by the sidenav-layout. The desired ou ...

Arrange two internal divs on top of one another with the option to maintain the float

While searching for a solution to my issue, I noticed that most responses involved removing the float property. However, since I am new to CSS, I would like to explore using float and see if it's the best approach. Here is the fiddle I've been w ...

How do I prevent a media query written for small screens from also affecting large screens?

@media only screen and (min-width: 320px), (min-width: 360px), (min-width: 375px), (min-width: 600px){ CSS properties for various screen widths are defined here } ...

Navigating Back to the Previous Page After Accepting an Alert Popup in Selenium

My testing process involves using Selenium with Python on a test page. Here is what happens during the test: First, I have page A open and then I click on a link that triggers the opening of page B. Upon submitting a form on page B, an alert popup ap ...

What is the best way to transfer a variable from the Cold Fusion back-end page to the HTML front-end section within a CFM file using jQuery Ajax?

My cfm file contains the necessary logic to extract a PDF and convert it into an image file. Now I am looking to pass the file path of this converted image to the front-end CFM so that it can be set as the source for the image tag below. <img id="image ...

Moving the words from textArea to each 'ol' element using JavaScript

When a word is entered in the textarea, it should be assigned to a specific class within an 'ol' tag. Each subsequent word will be placed in the next class sequentially. If there are no more words, the remaining classes should remain empty. <! ...

The date range picker displays the previous arrow but not the next arrow

I am currently using the DateRangePicker tool and for some reason, I am not seeing the arrow that should appear on the right side. I have double-checked my configuration but can't seem to figure out what is causing this issue. In the image attached, ...