PlotRange adjustments with BarChart
Good question. The problem is that the chart labels are placed as Text
objects inside the Graphics
body rather than as Ticks along an axis or frame. Further, the extent of the bars is not limited by the PlotRange. To get around this we can convert the Text
labels to Ticks
. (Version 7 does not appear to accept Placed[. . . , Axis]
as shown in kguler's answer or this could likely be simplified.)
Since the format of the output of BarChart
likely changes between version I shall describe what I am doing so that it can be adapted to other versions.
First I create a chart with additional options to yield the look desired:
ch =
BarChart[RandomReal[1, 10],
BarSpacing -> Large,
PlotRange -> {Automatic, {0.2, 1}},
PlotRangePadding -> {Automatic, 0},
PlotRangeClipping -> True,
ChartLabels -> Range@10
]
No labels are visible but they are present in the code itself. There is a GraphicsGroup
containing a series of Text
objects of the form:
Text[Pane[1], Offset[{0, -2}, {0.5, 0}], ImageScaled[{1/2, 1}]]
From these we can extract the label information:
labels = Cases[ch[[1]], Text[lbl_, Offset[_, {pos_, _}], ___] :> {pos, lbl, 0}, -4];
And then add them to the chart as tick labels:
Show[ch, Ticks -> {labels, Automatic}]
Update
In recent versions of Mathematica BarChart
defaults to Axes -> {False, True}
; the x axis must be drawn for the Tick labels to be displayed:
Show[ch, Ticks -> {labels}, Axes -> True]
Alternatively Frame
and FrameTicks
may be used as s0rce shows below.
edit (by s0rce):
I'm not sure why, but this wasn't working for me as is. However, I almost always use Frame->True
and when I did that everything worked (with some minor FrameTicks
and PlotRangePadding
adjustment).
ch =
BarChart[RandomReal[1, 10],
BarSpacing -> Large,
Frame -> True,
PlotRange -> {Automatic, {0.2, 1}},
PlotRangePadding -> {Automatic, 0},
PlotRangeClipping -> True,
ChartLabels -> Range@10
]
labels = Cases[ch[[1]],
Text[lbl_, Offset[_, {pos_, _}], ___] :> {pos, lbl, 0}, -4];
Show[ch, FrameTicks -> {labels, Automatic, False, False}]
Ok, you mean like this? Will clean this more, just wanted to know if this is what you wanted. If you do not want to move the origin also, you can remove the AxesOrigin -> {0, z}
from the code
Manipulate[
f[{{xmin_, xmax_}, {ymin_, ymax_}}, ___] :=
Module[{h = ymax - ymin, t},
t = If[z >= h, h, z];
Polygon[{{xmin, ymin + t}, {xmax, ymin + t}, {xmax, ymax}, {xmin, ymax}}]];
Grid[{
{
BarChart[data, BarSpacing -> Large, ImageSize -> 300,
ChartElementFunction -> f, PlotRange -> {All, {-5, 5}},AxesOrigin -> {0, z}],
BarChart[data, BarSpacing -> Large, ImageSize -> 300,
PlotRange -> {All, {-5, 5}}, ChartLabels -> Placed[Range[10], Below],
AxesOrigin -> {0, 0}]
}}],
{{z, 0.2, "z="}, 0, 3, .1, Appearance -> "Labeled"},
TrackedSymbols :> {z},
Initialization :>
{
data = RandomReal[{1, 5}, 10];
}
]