New demo of combined Bar and Line chart with left alignment
Written by Richard Heyes, RGraph author, on 17th September 2024
A recent support request asked for this - a combined
Bar
and
Line chart
with one key difference - the
Line chart
points are
left-aligned in each little section instead of being
center-aligned. You can see what is meant by this on
the chart below.
The first thing that's done by the code is create the
Bar chart
and Line chart
.
<script> // Here's the data for both the Bar chart and // also the Line chart data1 = [4,8,6,3,5,5,8]; data2 = [8,6,4,3,9,8,7]; // // Create and configure the Bar chart using // the data above. Crucially - don't call // the draw() function at the end. This will // be done by the CombinedChart object that // we create. // bar = new RGraph.Bar({ id: 'cvs', data: data1, options: { marginInner: 20, marginInnerGrouped: 5, backgroundGridVlines: false, backgroundGridBorder: false, xaxis: false, yaxis: false, xaxisLabels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'], textSize: 20 } }); // // Create and configure the Line chart using // the data from above. Again, - don't call // the draw() function at the end. The // CombinedChart object that we create will // do this. // line = new RGraph.Line({ id: 'cvs', data: data2, options: { colors: ['black'], spline: true, linewidth: 2, tickmarksStyle: 'filledcircle', tickmarksSize: 5 } }); // // Create the CombinedChart object that draws // the two objects on to the canvas. // new RGraph.CombinedChart(bar, line).draw(); </script>
So that code creates a regular, combined Bar
and Line chart
where the Line chart
points are centered
within each bar. This
is normally what you would want and expect to see. But now
we're going to left align the Line chart
points. It's very
easy to do
and just requires you to change the marginLeft
and marginRight
properties - essentially just
shifting the Line chart
left. You could
calculate the exact pixel value that you should use with the
marginLeft
and marginRight
settings
if you wanted to - and you might particularly want to do this
if you're using the responsive
property to support multiple
screen sizes (if you're doing this you'll probably need to
use the responsive
callback to update the new margins that
should be used when the screen size changes)
<script> // // Move the Line chart left so its points are left // aligned with the bars (now that the CombinedChart // object has done its thing). This could be calculated // from the Bar chart coordinates but here it's just an // approximate value. // line.set('marginLeft', 15); // Decrease this line.set('marginRight', 55); // Increase this // Redraw the canvas so that the Line chart will // now use the updated margin sizes. RGraph.redraw(); </script>