Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stacked bar chart #10

Closed
lpilon opened this issue Mar 18, 2013 · 50 comments
Closed

Stacked bar chart #10

lpilon opened this issue Mar 18, 2013 · 50 comments

Comments

@lpilon
Copy link

lpilon commented Mar 18, 2013

Awesome lib, thanks for coding! Any chance for a stacked bar chart?

@nnnick
Copy link
Member

nnnick commented Mar 18, 2013

Will be looking to add different chart types in the future. I'll aim to extract different chart types into a packager app, so you can pick and choose what charts you want to include.

@jarthod
Copy link

jarthod commented Mar 18, 2013

This great, nice work!
I'm also looking for stacked bar/line chart, let me know if I can help ;)

@Sigler
Copy link

Sigler commented Mar 19, 2013

That would be great. Would love to switch to this from Highcharts but need stacked bars and stacked area charts. Great work so far!

@reinpk
Copy link

reinpk commented Mar 20, 2013

+1 on both stacked bar charts and stacked line area plots

@bmconklin
Copy link

I threw something together for the stacked bar chart overnight. It's basically a hacked version of the original bar chart, so it runs off the same data, just puts one on top of the other rather than next to. It seems to work just fine with any positive data, I've tested up to 6 data sets, but negative data sets are not yet supported. I have submitted a pull request.

3stack

@aeosynth
Copy link

👍

#37 is @Verran42's pr

@pinara747
Copy link

any plans for tooltip integration for this?

@gambogi
Copy link

gambogi commented May 29, 2013

Bump, was just about to implement this myself.

@capripot
Copy link

Maybe we can think about the packager after, and include this cool feature first !?

@jairtrejo
Copy link

An implementation on top of the existing bar chart (setting the option stacked: true): #168

@schultzter
Copy link

Another cool variation would be percent stacked bar charts where the bars all the same height (100%) but the sections vary according to proportion of the components.

@docbillnet
Copy link

It looks like this solution needs an extreme amount of work. Is is an example I just ran with this version of chart.js, and then the plot using the same data with google analytics.
chart_js
googleanalytics

@docbillnet
Copy link

The biggest problem you'll see is the stacked chart.js is using a minimum box size for every data value, and then summing those values. So in my 60% column where all the values are too small to even be visible, it gets total up to a over 2,000,000. The actual total for that column is 47.25. This bug should be fairly trivial to fix. What requires a lot of work is finding a way to format the charts js version to look nearly as pretty as the google version... I don't even see an option to make the bar widths wider, or at least appear directly above the labels...

Adding a legend off to the side is also extra manual work... I think it is possible to reform the numbers to have comma thousand separators in chart.js, but it doesn't happen by default.

@jairtrejo
Copy link

@docbillnet Do you have the dataset? Might it work with #168 ?

@docbillnet
Copy link

#168 has the same basic bug. It is calculating a yOffset by adding bar heights, which is a rounded up value with offsets added for a minimum size. So there is both accumulation of the minimum values and cumulative round-off error from each value. Preferably what it should do instead is keep track of total data value, and then calculate the yoffset based that... That way there would be no cumulative effect.

That said, it looks like #168 might get the bar widths correct, I will try it and see if it is a step in the right direction.

@docbillnet
Copy link

Looks like I was wrong. #168 probably has cumulative round-off error (I'll have to look more carefully), but it does not accumulate a minimum size. So if I could figure out how to stretch the width of the bars to fill up the space, this would not be half bad.

chart_js

@jairtrejo
Copy link

I think I intentionally accounted for the minimum-size accumulation error. I'm not sure why the bars get narrow, but I'll give it a look.

@docbillnet
Copy link

Setting barStrokeWidth to 0 makes the bars much wider. I'm not sure why data.datasets.length would be included at all in the barWidth calculation when stacked. That is probably a bug. Looking closer, it looks like yOffset is not a rounded value, so there should not be an accumulated error like I was expecting.

@jairtrejo
Copy link

Hi! You are right, that was a bug. I removed that configuration and fixed an horizontal misalignment. I also made it so that stacked charts would start at zero.

Could you check again, please?

@docbillnet
Copy link

The fun with building from live data (from a test system), the data used has changed. So I'll show both again. As you can see chart.js is looking much better than before. :)

google-analytics

chart_js

@jairtrejo
Copy link

Indeed! I'll try and implement the thousand separators in my fork, but I guess all this work will have to be redone after the big refactor.

@jphellemons
Copy link

I have this nice bar chart with 4 datasets (each year a set) and would like to have one year as stacked. So in total for one month, four different datasets which are stacked. Is that possible, or will it be possible in the upcoming release?
av8velb

@jairtrejo
Copy link

@jphellemons it is posible with my fork #168

Something like:

var data = {
    labels: ['January', 'February', 'March', 'April'],
    datasets: [
        {
            // 2012
            fillColor: '#EF2929',
            strokeColor: '#CCC',
            data: [60, 30, 25, 82]
        },
        {
            // 2013
            fillColor: '#729FCF',
            strokeColor: '#CCC',
            data: [40, 20, 75, 12]
        },
        {
            // 2014
            fillColor: '#FCE94F',
            strokeColor: '#CCC',
            data: [22, 34, 75, 92]
        },
        {
            // 2015
            fillColor: '#AD7FA8',
            strokeColor: '#CCC',
            data: [10, 34, 65, 42]
        },
    ]
};

var ctx = document.getElementById('bars').getContext('2d');
var chart = new Chart(ctx).Bar(data, {stacked: true});

Notice the {stacked: true} option.

@jphellemons
Copy link

Thank you @jairtrejo but I meant something like this:

var data = {
    labels: ['January', 'February', 'March', 'April'],
    datasets: [
        {
            // 2012
            fillColor: '#EF2929',
            strokeColor: '#CCC',
            data: [[60,20,20], [30,10,5], [25], [82,1,13]]
        },
        {
            // 2013
            fillColor: '#729FCF',
            strokeColor: '#CCC',
            data: [[40,2], [20,23,34], [75,4], [12,10,10,10,10]]
        } ]
};

@jairtrejo
Copy link

Oh! I see. You mean multiple stacked bar charts per month. I am affraid it
can't be done right now 😔

2014-02-06 JP Hellemons notifications@github.com:

Thank you @jairtrejo https://github.com/jairtrejo but I meant something
like this:

var data = {
labels: ['January', 'February', 'March', 'April'],
datasets: [
{
// 2012
fillColor: '#EF2929',
strokeColor: '#CCC',
data: [[60,20,20], [30,10,5], [25], [82,1,13]]
},
{
// 2013
fillColor: '#729FCF',
strokeColor: '#CCC',
data: [[40,2], [20,23,34], [75,4], [12,10,10,10,10]]
} ]
};

Reply to this email directly or view it on GitHubhttps://github.com//issues/10#issuecomment-34299313
.

Jair Trejo
http://jairtrejo.mx

@ghost
Copy link

ghost commented Feb 12, 2014

Hi,

Is there a way to get the scale labels on the right instead of the left?

Currently I use 2 canvases to mix Line and Bar, is there a better way?

Cheers,

Marcel

@nnnick
Copy link
Member

nnnick commented Jun 29, 2014

This would be a perfect opportunity for someone to create a new chart type extension to the library. See http://www.chartjs.org/docs/#advanced-usage-writing-new-chart-types for some details.

You could reuse/extend the Chart.Rectangle class to reuse the same code for hit detection too. 👍

@nnnick nnnick closed this as completed Jun 29, 2014
@nnnick
Copy link
Member

nnnick commented Jul 31, 2014

@mantisory
Copy link

so, was there ever support given for negative values?

@tannerlinsley
Copy link
Contributor

Ditto, @mantisory. +1 for negative values for sure.

@jitendersaini
Copy link

Hi All,
Thank you very much for such a useful posts here,
I'm a new user to Chart.js api. My requirement is, I want to show Stacked bar chart with X-axis and Y-axis overlapped with Line chart. Please refer the image link below that something I want. I managed to generate stacked bar chart using Chart.StackedBar.js plugin but I need Line chart overlapped with stacked barchart along with Y axis. Please someone help.
Thanks
Jitender
capture

@vjanssens
Copy link

@jitendersaini have you been able to accomplish your described chart? I'm in need of something similar.

@jitendersaini
Copy link

@vjanssens, No actually not yet, that's why I switched to Highcharts.

@TheXardas
Copy link

Highcharts costs a lot.
I need around the same as jitendersaini, but with simple horizontal line.
I guess i'll try to draw it manually with canvas, if nobody had the same solution yet..

@etimberg
Copy link
Member

etimberg commented Oct 7, 2015

@TheXardas creating a chart like @jitendersaini wanted is possible using the v2.x branch. The combo sample shows how to put bars and lines on the same chart. You could use the stacked sample to see how to make stacked bars and combining the two should give you what you are looking for,

@TheXardas
Copy link

@etimberg you rock, man! That's just what i need, and i was able to run it in minutes. Thanks!

@ericjgruber
Copy link

Curious, is there an easy way to place the numbers at the top of the bar chart instead of at the bottom? Maybe I'm missing it.

@etimberg
Copy link
Member

@vml-egruber which numbers are you referring to?

@ericjgruber
Copy link

@etimberg Sorry, I was referring to the numbers on the x-axis at the bottom.

@etimberg
Copy link
Member

@vml-egruber this is possible using v2 but not possible in v1. In v2, include the following in your config.

scales: {
    xAxes: [{
        position: 'top' 
    }] 
} 

@ericjgruber
Copy link

Sweet, thanks!

@cdwilhelm
Copy link

@TheXardas do you have a fiddle you could share to show how to combine a stacked chart with lines. this is what i have, but it's not quite right
https://fiddle.jshell.net/cwilhelm/whva3opt/

@TheXardas
Copy link

@cdwilhelm that is exactly the way, that i was able to do it. Why is it not right for you case?

@sahil290791
Copy link

Is there a way to customize the tooltip for stacked charts, right now it shows color, number(y-axis value) and x-axis label or is it possible to assign a label for each stack shown in a bar. Like: red- 200 Blogs, green- 300 Discussions etc. Basically assigning label to each color.

@yoseppiedro
Copy link

Hello everyone..
I'm looking for stacked bar chart and multiple line combination like this (Highchart) but with stacked bar chart:
image

But when I tried to use chart.js to achieve this my line chart also become stacked while sometimes line could be crossing each other..
this is my stacked bar with line :
image

is there anyone could help?

@Sabyasachi18
Copy link

Hi All!..Anyone could help me in creating a waterfall chart from bar charts?

@heinduplessis
Copy link

heinduplessis commented Aug 16, 2016

Ok, here's a unique thing on the internet as of today, a sample of a stacked bar chart using chart.js. Attached.

Uploading Stack2.zip…

@MartinKei
Copy link

Guys, @etimberg is right, just combine the two examples. As a whole this would look like this:

screen shot 2016-09-21 at 14 11 33

<!doctype html>
<html>

<head>
    <title>Stacked Bar Chart</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="../dist/Chart.bundle.js"></script>
    <style>
    canvas {
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
    }
    </style>
</head>

<body>
    <div style="width: 75%">
        <canvas id="canvas"></canvas>
    </div>
    <button id="randomizeData">Randomize Data</button>
    <script>
        var randomScalingFactor = function() {
            return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
        };
        var randomColorFactor = function() {
            return Math.round(Math.random() * 255);
        };

        var barChartData = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [{
                type: 'bar',
                label: 'Dataset 1',
                backgroundColor: "rgba(220,220,220,0.5)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            }, {
                type: 'bar',
                label: 'Dataset 2',
                backgroundColor: "rgba(151,187,205,0.5)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            }, {
                type: 'bar',
                label: 'Dataset 3',
                backgroundColor: "rgba(151,187,205,0.5)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()]
            }, {
                type: 'line',
                label: 'Dataset 4',
                backgroundColor: "rgba(151,187,205,0.5)",
                data: [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()],
                borderColor: 'white',
                borderWidth: 2
            }]

        };
        window.onload = function() {
            var ctx = document.getElementById("canvas").getContext("2d");
            window.myBar = new Chart(ctx, {
                type: 'bar',
                data: barChartData,
                options: {
                    title:{
                        display:true,
                        text:"Chart.js Bar Chart - Stacked"
                    },
                    tooltips: {
                        mode: 'label'
                    },
                    responsive: true,
                    scales: {
                        xAxes: [{
                            stacked: true,
                        }],
                        yAxes: [{
                            stacked: true
                        }]
                    }
                }
            });
        };

        $('#randomizeData').click(function() {
            $.each(barChartData.datasets, function(i, dataset) {
                dataset.backgroundColor = 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',.7)';
                dataset.data = [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()];

            });
            window.myBar.update();
        });
    </script>
</body>

</html>

@aissaghouti
Copy link

@andras-gyarmati
Copy link

Setting barStrokeWidth to 0 makes the bars much wider. I'm not sure why data.datasets.length would be included at all in the barWidth calculation when stacked. That is probably a bug. Looking closer, it looks like yOffset is not a rounded value, so there should not be an accumulated error like I was expecting.

if you set stacking true on x axes it does not get narrow (at least it worked for me without any negative side effects on version 9)

kurkle referenced this issue in kurkle/Chart.js Apr 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests