Re-write stacked histogram (fixes bugs)

This is a second try at #1706. I think it resolves all of the issues with that PR.

This is re-write of how stacked histograms are handled. It should fix #1679 and #1631, which both came about because of the way that stacked histograms were handled, starting in #847.

I've also added tests that should catch both bugs if they pop up again.