# How to Add Inner Squares to Bar Chart Using BarChart[] Function?

I need to create a couple of bar charts, and I'm using the BarChart built-in function.

Currently, I have managed to make them look like the image on the left.

BarChart[Range[5], BarSpacing -> None, AspectRatio -> {1, 1}]


However, I would like to add the inner squares to each bar on the chart (as shown in the image on the right), and I'm not sure how to achieve this.

Any ideas? I would like to avoid using another function if possible.

• How would you like the result look like when input is data where SeedRandom[3]; data = RandomReal[10, 5];?
– kglr
Commented Sep 25, 2023 at 18:52
• From now I'm just working in discrete values. Commented Sep 25, 2023 at 19:12

### 1. ChartElementFunction

We can use a custom ChartElementFunction to add lines to rectangles:

ClearAll[cEF]
cEF = Module[{xr = #[[1]]},
{ChartElementData["Rectangle"][##],
Directive[CapForm["Butt"], Black, Thickness[Small], Opacity[0.67]],
If[#[[2, 2]] > 0, Map[Line[Thread[{xr, #}]] &]@Most@Range[#[[2, 2]]], {}]}] &;


Examples:

dt1 = Range[5];

BarChart[dt1, AspectRatio -> 1,  BarSpacing -> {0, 0},
ChartElementFunction -> cEF]


SeedRandom[7];

dt2 = RandomInteger[12, 7];

BarChart[dt2, AspectRatio -> 1,  BarSpacing -> {0, 0},
ChartElementFunction -> cEF]


### 2. ChartElements

BarChart[Range[5],
ChartElements ->
Graphics[Rectangle[], PlotRangePadding -> 0, ImagePadding -> None],
AspectRatio -> 1,
BarSpacing -> {0, 0}]


• Do you know how to make the adjacent edges truly overlap with each other? Please note that some of them appear slightly thicker. At this scale, it may be barely noticeable, but if you, for instance, add the option ImageSize -> 800, you will observe that there is still a slight gap between each square. Furthermore, at very small scales like 80, it seems that the squares don't have the same size. Commented Sep 25, 2023 at 17:54
• @DanielCheca, unfortunately i don't know a way to make rectangle truly overlap using the option ChartElements. It may be easier to add the desired line using a custom ChartElementFunction.
– kglr
Commented Sep 25, 2023 at 18:26
Needs["NDSolveFEM"];

addLines = ReplaceAll[r: Rectangle[a_, b_, __] :>
{r, First @
ToElementMesh[Rectangle[a, b],
"MeshOrder" -> 1, MaxCellMeasure -> {"Length" -> 1}]["Wireframe"]}]


Examples:

dt1 = Range[5];

BarChart[Range[5], DisplayFunction -> addLines,
AspectRatio -> 1, BarSpacing -> {0, 0}]


SeedRandom[7];

dt2 = RandomInteger[12, 7];

BarChart[dt2, DisplayFunction -> addLines,
AspectRatio -> 1, BarSpacing -> {0, 0}]