Alfredo Sánchez
Alfredo Sánchez

Reputation: 735

Reverse x-axis in one of two faceted ggplots

I want to plot two grids corresponding to macula of retina of eyes (R and L). The position of cells should be this

enter image description here

I can get the plot below with ggplot2

width <- rnorm(128)
row <- rep(rep(seq(1,8),8),2)
col <- rep(unlist(lapply(seq(1,8), rep, 8)))
cell <- paste0(row, ".", col)
eye <- factor(c(rep("R", 64), rep("L", 64)), levels = c("R","L"))
data <- data.frame(x, row, col, cell, eye)
ggplot(data = data, aes(x=col, y=row, fill=width)) + 
geom_tile() + 
geom_text(aes(label=cell)) + 
facet_grid(.~eye) +
ggtitle("Macular grids") 

enter image description here

but I need to reverse the x-axis of the grid corresponding to the left eye only.

I want to do it with facets if possible, that is, without grid.arrange.

Upvotes: 1

Views: 323

Answers (1)

Richard Telford
Richard Telford

Reputation: 9923

This is possible if you make your x variable into a factor after pasting either R or L onto the number. The order of the factor can be specified and the letter removed in scale_x_manual

width <- rnorm(128)
row <- rep(rep(seq(1,8),8),2)
col <- rep(1:8, each = 8)
cell <- paste0(row, ".", col)
eye <- factor(rep(c("R", "L"), each = 64), levels = c("R","L"))
data <- data.frame(width, row, col, cell, eye) %>% 
  mutate(col2 = paste0(col, eye),
         col2 = factor(col2, levels = c(paste0(8:1, "R"), paste0(1:8,"L")))) 



ggplot(data = data, aes(x=col2, y=row, fill=width)) + 
  geom_tile() + 
  geom_text(aes(label=cell)) + 
  scale_x_discrete(label = function(str){substring(str, 1, 1)}) +
  facet_grid(.~eye, scales = "free_x") +
  ggtitle("Macular grids") 

enter image description here

Upvotes: 1

Related Questions