I was looking for a way to make a stacked bar chart, where a bar shows the forecast and the real quantity as the part of the forecast. So, if the forecasted quantity is 10 and the real quantity is 5, then the bar height should be 10. Instead, it makes it 15, so adds up one quantity to another. Is there a way to proceed other than making additional calculations (such as calculating forecasted quantity minus real quantity and using the results instead of initial forecasted quantity?).
$\begingroup$
$\endgroup$
4
-
1$\begingroup$ You could use the ChartLayout option "Overlapped" rather than "Stacked" but the larger one will obscure the smaller one if the data isn't properly ordered. $\endgroup$– Mark RCommented Jun 23, 2019 at 18:48
-
$\begingroup$ Interestingly, if you use Associations for the data, Overlapped doesn't obscure the smaller. Such as this: BarChart[{Association@{"forecast" -> 10, "actual" -> 5}, Association@{"forecast" -> 30, "actual" -> 10}}, ChartLayout -> "Overlapped"] $\endgroup$– Mark RCommented Jun 23, 2019 at 18:53
-
$\begingroup$ Thanks you very much $\endgroup$– Liza BelyaevaCommented Jun 23, 2019 at 20:00
-
$\begingroup$ I used data from @kglr and my statement about using an association to make the data visible is wrong. Use the method below to make it work. $\endgroup$– Mark RCommented Jun 24, 2019 at 0:22
Add a comment
|
1 Answer
$\begingroup$
$\endgroup$
2
If we use the option setting ChartLayout -> "Overlapped"
, some bars may become invisible:
data = {{10, 5}, {5, 10}, {15, 8}, {8, 12}};
colors = {Blue, Yellow};
legendlabels = {"actual", "forecast"};
BarChart[data,
ChartLayout -> "Overlapped",
ChartStyle -> colors,
ChartLegends -> legendlabels]
To make all bars visible we can use the approach in this answer to define a function to pre-process input data into a form so that all bars are visible in BarChart
output:
ClearAll[reArrange]
reArrange[dat_, cols_] := Map[SortBy[-First @ # &]]@
Transpose @ MapThread[Thread @* Style, {Transpose @ dat, cols}];
datamodified = reArrange[data, colors];
BarChart[datamodified,
ChartLayout -> "Overlapped",
ChartLegends -> SwatchLegend[colors, legendlabels]]
-
1$\begingroup$ I like this solution but the color overlap seems slightly confusing. Perhaps using opacity for color helps make this more obvious. Such as this: colors = {Opacity[.5, Blue], Opacity[.5, Yellow]}; But this is just an opinion. $\endgroup$– Mark RCommented Jun 24, 2019 at 0:20
-
$\begingroup$ @MarkR, using opacity is a good idea. $\endgroup$– kglrCommented Jun 24, 2019 at 1:20