Je veux annoter du texte sur la dernière facette du tracé avec le code suivant:
library(ggplot2) p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() p <- p + facet_grid(. ~ cyl) p <- p + annotate("text", label = "Test", size = 4, x = 15, y = 5) print(p)
Mais ce code annote le texte sur chaque facette. J’apprécierais beaucoup si vous me guidez comment obtenir le texte annoté sur une seule facette. Merci d’avance.
Typiquement, vous feriez quelque chose comme ceci:
ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text", cyl = factor(8,levels = c("4","6","8"))) p + geom_text(data = ann_text,label = "Text")
Il devrait fonctionner sans spécifier la variable factor, mais émettra probablement des avertissements:
Voici l’insortinggue sans annotations de texte:
library(ggplot2) p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl) + theme(panel.spacing = unit(1, "lines")) p
Créons un bloc de données supplémentaire pour contenir les annotations de texte:
dat_text <- data.frame( label = c("4 cylinders", "6 cylinders", "8 cylinders"), cyl = c(4, 6, 8) ) p + geom_text( data = dat_text, mapping = aes(x = -Inf, y = -Inf, label = label), hjust = -0.1, vjust = -1 )
Alternativement, nous pouvons spécifier manuellement la position de chaque étiquette:
dat_text <- data.frame( label = c("4 cylinders", "6 cylinders", "8 cylinders"), cyl = c(4, 6, 8), x = c(20, 27.5, 25), y = c(4, 4, 4.5) ) p + geom_text(data = ann_text,label = "Text") p + geom_text( data = dat_text, mapping = aes(x = x, y = y, label = label) )
Remarques:
-Inf
et Inf
pour positionner le texte sur les bords d'un panneau. hjust
et vjust
pour ajuster la justification du texte. dat_text
données étiquette de texte dat_text
doit avoir une colonne qui fonctionne avec facet_grid()
ou facet_wrap()
. Je pense que pour la réponse ci-dessus lab = “Text” est inutile, le code ci-dessous est également correct.
ann_text <- data.frame(mpg = 15,wt = 5, cyl = factor(8,levels = c("4","6","8"))) p + geom_text(data = ann_text,label = "Text" )
Cependant, si vous souhaitez étiqueter différemment dans différents sous-graphes, cela se déroulera comme suit:
ann_text <- data.frame(mpg = c(14,15),wt = c(4,5),lab=c("text1","text2"), cyl = factor(c(6,8),levels = c("4","6","8"))) p + geom_text(data = ann_text,aes(label =lab) )