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
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
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
Can you just add the labels to your original data?
new_df <- data.frame(f = as.factor(rep(1:2, 15)), x = rnorm(30), y = runif(30), label = c("X1","X2"))
g <- ggplot(data = new_df, aes(x = x, y = y)) + geom_point()
g <- g + facet_grid(. ~ f)
g <- g+ geom_text(mapping = aes(x = Inf, y = -Inf, label = label),
hjust = 1.1, vjust = -1.1)
g
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.