5

With the following code, I obtain text on each facet but the text is superimposed : "X1" and "X2" are superimposed on each facet. Where is the problem in my code ?

R code :

new_df <- data.frame(f = as.factor(rep(1:2, 15)), x = rnorm(30), y = runif(30))
g <- ggplot(data = new_df, aes(x = x, y = y)) + geom_point() 
g <- g + facet_grid(. ~ f)
g
label_graph <- data.frame(label = c("X1", "X2"))

g <- g + geom_text(data = label_graph,
                    mapping = aes(x = Inf, y = -Inf, label = label),
                    hjust = 1.1, vjust = -1.1)
g
Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
Sebastien
  • 51
  • 1
  • If one of the answers provided solved your issue, then please indicate this by clicking on the checkmark under the voting buttons for the answer. – Claus Wilke Nov 09 '19 at 20:41

2 Answers2

3

you need to add the column f to your label_graph, this way once the facet is applied, the labels are on the designated facet

new_df <- data.frame(f = as.factor(rep(1:2, 15)), x = rnorm(30), y = runif(30))
g <- ggplot(data = new_df, aes(x = x, y = y)) + geom_point() 
g <- g + facet_grid(. ~ f)
label_graph <- data.frame(label = c("X1", "X2"),f=factor(1:2))

g <- g + geom_text(data = label_graph,
                    mapping = aes(x = Inf, y = -Inf, label = label),
                    hjust = 1.1, vjust = -1.1)
g

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72
2

Is it an option for you to label the facet headers directly instead of labelling the bottom corners? Your example suggests that may be a better solution. If that works for your actual use case, you may simply change your f column directly by pasting the X, and you get:

new_df <- data.frame(f = as.factor(paste0("X", rep(1:2, 15))), x = rnorm(30), y = runif(30))
g <- ggplot(data = new_df, aes(x = x, y = y)) + geom_point() 
g <- g + facet_grid(. ~ f)
g

facetlabels

MSR
  • 2,731
  • 1
  • 14
  • 24
  • Thanks a lot. In fact, I was looking for a method to differentiate facet headers and specific text for each header. – Sebastien Nov 09 '19 at 16:08