Reputation: 57
So i need to create a basic bar graph from scratch using javascript, i tried setting some things such as, I attempted to start trying to define some values but it all went wrong.
The task is to create a program that will accept some of this data, input by the user, and to produce a graph that is suitably formatted. The output could be made to look like this:
Here is the data that is provided
How would I simply even attempt this from scratch?
Upvotes: 0
Views: 5759
Reputation: 7184
Given all the complexities of charting, I think most people just use one of the many open source charting libraries. SparkLines is just one example.
Yet, sometimes you just want a simple chart without adding a library. And a bar chart is one of the easiest to build. The code snippet below is very basic, but it is enough to get OP started with the homework assignment.
Run code snippet to view:
<html>
<body>
<style type="text/css">
#chart {background-color: lightyellow; position: relative; height:200px; width: 200px; border: 1px black solid; display: table-cell; vertical-align: bottom; font-size: 10px; }
.bar {position: absolute; bottom: 0; display:inline-block; width: 10px; margin: 2px; background-color: lightpink;}
</style>
<div id="chart"></div>
<script type="text/javascript">
var i, max, min, h, html='', data = [34.7,68.9,65.1,130.2,208.6,172.8,155.0,168.6,134.4,52.7,94.5,41.5];
max = min = data[0];
for(i=0; i<data.length; i++) {
if (max < data[i]) max = data[i];
if (min > data[i]) min = data[i];
}
for(i=0; i< data.length; i++) {
h = Math.round( 100 * ((data[i] - min) / max));
html += '<div class="bar" style="height:' + h + '%; left:' + (12 * i) + 'px">' + data[i] + '</div>';
}
document.getElementById('chart').innerHTML = html;
</script>
</body>
</html>
Upvotes: 3
Reputation: 2566
Calculate the height in pixels that each group has with the rule of three:
320 = 200
pixel-y = group-y
Paint the respective group on your graph
For example, if a group has a Y value of 120:
320 = 200
pixel-y = 120
pixel-y = (320 * 120) / 200
pixel-y = 192
Upvotes: 0