Annotating text on individual facet in ggplot2 using geom_text

杀马特。学长 韩版系。学妹 提交于 2020-01-14 13:57:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!