User247365
User247365

Reputation: 685

Restructure geom_tile ggplot2

I have a 4x4 geom_tile plot where the upper right cell contains an additional 4x4 cell. I am wanting the plot to appear as it does below.

Desired output visuals

The positions are listed inside the cells for clarity, however, the code makes the data value corresponding with the position placed in the cell. The sample code I provided currently produces this:

Current ggplot output

I am not able to manipulate the data values in terms of position (values for x and y cannot be changed) and the cell containing additional breakdown will not always be in the upper right so a solution that does not hardcode this location in would be appreciated.

If this is possible I would greatly appreciate any assistance you can provide!

x <- c(0,0,1,0.5,0.5,1,1)
y <- c(0,1,0,0.5,1,0.5,1)
data_val <- sample(0:100, 7)
alldata <-data.frame(x, y, data_val)


    ggplot(data= alldata, aes(x, y)) +
    geom_tile(colour = "black") + 
    geom_text(aes(label = data_val),colour="white")

Upvotes: 2

Views: 366

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

This requires a slight change to your notation, so that x and y correctly locate the centre of each square, and an additional width parameter (which with this system really only depends on whether x and y are even or odd). For other quartered squares, use -1/+1 instead of 3/5 as appropriate.

x <- c(0,0,4,3,3,5,5)
y <- c(0,4,0,3,5,3,5)
w <- ifelse(x%%2==0, 4, 2)
data_val <- sample(0:100, 7)
alldata <- data.frame(x, y, w, data_val)

ggplot(data= alldata, aes(x=x, y=y, width=w, height=w)) +
  geom_tile(fill = "white", color="black") + 
  geom_text(aes(label = data_val), colour="black") +
  coord_fixed()

enter image description here

Upvotes: 3

Related Questions