# Combining two region as one with boundaries: combining rectangle:

If I have the following two regions:

r1 = Rectangle[{0, 0}, {5, 10}]
r2 = Rectangle[{5, 0}, {15, 10}]


to combine them I can use,

RegionPlot[RegionUnion[r1, r2]]


which gives,

how can we add two regions with their boundaries still showing, for example in the following,

I added the black line by myself.

• E.g. RegionPlot[{r1, r2}, PlotStyle -> LightBlue] or even RegionPlot[{r1, r2}, PlotStyle -> LightBlue, BoundaryStyle -> Black] Commented Feb 4, 2023 at 15:48
• Thanks! Not exactly there is a difference in showing two regions in plotting and joining them as one region.
– a019
Commented Feb 4, 2023 at 15:53

Taking into consideration the comment by the author of the OP

Not exactly there is a difference in showing two regions in plotting and joining them as one region.

my suggested solution is the following:

Show[RegionPlot[RegionUnion[r1,r2]],Graphics[Line[Catenate@KeyValueMap[ConstantArray]@MapThread[Min,KeyIntersection[Counts/@{MeshCoordinates@r1, MeshCoordinates@r2}]]]]]


Commentary:

Given the two rectangles

r1 = Rectangle[{0, 0}, {5, 10}];
r2 = Rectangle[{5, 0}, {15, 10}];


we can use MeshCoordinates to get a list of their coordinates

l1 = MeshCoordinates@r1
l2 = MeshCoordinates@r2


Now, we have two lists of lists of the schematic form {{x1,y1},{x2,y2}..}. In order to find the boundary of the rectangles, all we need to do is find those sublists from the above that are pairwise equal. This can be achieved as follows:

Catenate@KeyValueMap[ConstantArray]@MapThread[Min,KeyIntersection[Counts/@ {l1, l2}]]


Now, we have all we need to define the Line that represents the boundary. We wrap it with Graphics

line = Graphics[
Line[Catenate@
KeyValueMap[ConstantArray]@
KeyIntersection[
Counts /@ {l1,l2}]]]];


Finally, as requested we use RegionUnion to join the regions and then just show the boundary and joined regions

Show[RegionPlot[RegionUnion[r1, r2]], line]


You could construct a mesh region manually:

MeshRegion[
Join[MeshCoordinates[r1], MeshCoordinates[r2]], { MeshCells[r1, 2],
Map[# + MeshCellCount[r1, 0] &, MeshCells[r2, 2], {2}]}]