3
$\begingroup$

Is there a way to get BarChart to position any number of bars of arbitrary widths at arbitrary positions? e.g. I want to plot normal vertically-standing bars, with bar number one spanning from 1 to 3 of the horizontal axis, and bar number two spanning from 2 to 5, and so on.

$\endgroup$
1
  • $\begingroup$ Look at Histogram and its bin width specification bspec. $\endgroup$
    – Edmund
    Commented Jul 25, 2015 at 10:49

1 Answer 1

4
$\begingroup$

Update: You can also use a custom ChartElementFunction and pass the rectangle starting positions as metadata:

ceF[ced_ : "Rectangle"] := 
   ChartElementData[ced][{{#3[[1]], #3[[1]] + (#[[1, 2]] - #[[1, 1]])}, #[[2]]}, ##2] &

Examples:

data = {{2, 1}, {3, 4}};
positions = {1, 2};
ticks = Range[positions[[-1]] + data[[-1, -1]]];

RectangleChart[Thread[data -> positions], 
  ChartStyle -> 97, ChartBaseStyle -> Opacity[.6],
  Frame -> True, FrameTicks -> {{Automatic, Automatic}, {ticks, Automatic}}, 
  ChartElementFunction -> ceF[]]

enter image description here

With positions = {2, 7} and ChartElementFunction -> ceF["GlassRectangle"] we get

enter image description here

SeedRandom[77]
data = RandomInteger[{1, 5}, {5, 2}];
positions = Sort @ RandomSample[Range @ 20, 5];
ticks = Range[positions[[-1]] + data[[-1, -1]]];

RectangleChart[Thread[data -> positions], 
 ChartStyle -> "Rainbow", ChartBaseStyle -> Opacity[.6],
 Frame -> True, FrameTicks -> {{Automatic, Automatic}, {ticks, Automatic}},
 ChartElementFunction -> ceF["FadingRectangle"]]

enter image description here

Original answer:

You can use RectangleChart with the option setting BarSpacing->-1:

opts1 = {BarSpacing -> -1, ChartStyle -> {Opacity[.5, Red], Opacity[.5, Green]}};

rc1 = RectangleChart[{{2, 1}, {3, 4}}, opts1]

Mathematica graphics

To add the ticks to the horizontal axis:

opts2 = Join[opts1, {Frame -> {True, True, False, False}, 
    FrameTicks -> {{#, # + 1} & /@ Range[-1, 5], Automatic, None, None},
    PlotRange -> {{-1, 4}, {0, 4}}, AxesOrigin -> {-1, 0}}];

rc2 = RectangleChart[{{2, 1}, {3, 4}}, opts2]

Mathematica graphics

Post-process if you wish to remove the extra lines and ticks below the bars:

rc2 /. Line[__] :> {}

Mathematica graphics

$\endgroup$
3
  • $\begingroup$ Thanks for this answer, which indeed produces the example I gave. I've updated the question to emphasise that I seek arbitrary widths and spacings. I think I may just need to use Graphics with Rectangle. $\endgroup$ Commented Jul 26, 2015 at 13:33
  • $\begingroup$ @CarbonFlambe, does the updated version answer your question? $\endgroup$
    – kglr
    Commented Feb 12, 2019 at 10:13
  • $\begingroup$ Yes indeed -- thanks! $\endgroup$ Commented Feb 13, 2019 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.