问题
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
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/58780724/annotating-text-on-individual-facet-in-ggplot2-using-geom-text