我正在尝试使用文本标注facet,但它们在每个Facet中重叠,而不是一个一个地显示。这是我一直在使用的代码:
ggplot(df) +
aes(x = xvalues, y = yvalues) +
geom_point(size = 1, shape = 1) +
facet_wrap(~ model_f, ncol = 3) +
geom_text(data = df2, aes(x = 33, y = 2.2, label = test),
parse = TRUE, check_overlap = FALSE)
因此,根据我的数据,我应该有6个图(根据我的数据中的model_f
列绘制),我得到了。但是当我尝试将geom_text
函数与数据框一起使用时:
df2 <- data.frame(test = c("one", "two", "three", "four", "five", "six"))
每个方面图都获得所有字符串,但彼此重叠。如果我使用check_overlap = TRUE
函数,我只得到每个Facet中的第一个元素,即“one”。
如何使文字标签分别显示在每个方面?
答案 0 :(得分:3)
如果您创建用于添加标签的数据框,则此数据还必须具有构面数据的列。以虹膜数据集为例:
label_text <- data.frame(lab=c("Label 1","Label 2","Label 3"),
Species = levels(iris$Species))
创建以下数据框:
lab Species
1 Label 1 setosa
2 Label 2 versicolor
3 Label 3 virginica
然后我们可以绘制图表:
ggplot(iris) +
aes(x = Sepal.Length, y = Sepal.Width) +
geom_point(size = 1, shape = 1, aes(col = Species)) +
facet_wrap(~ Species, ncol = 3) +
geom_text(data = label_text, x = 6.2, y = Inf, aes(label = lab), vjust = 2)
要改变图表上标签的位置,您可以更改标签geom_text
参数中的x和y坐标。
您可以在绘制图形之前更改构面名称,而不是将标签添加到绘图中:
# First we merge the label data as a column to the full dataset
df <- merge(iris, label_text, by = "Species")
# Then we create our label name
df$facet <- paste0(df$Species, "\n (stat = ", df$lab, ")")
# Plot the results
ggplot(df) +
aes(x = Sepal.Length, y = Sepal.Width) +
geom_point(size = 1, shape = 1, aes(col = Species)) +
facet_wrap(~ facet, ncol = 3) +
theme(legend.position = "none")
我个人更喜欢第二种技术,因为您无需担心手动指定坐标。