Facet 图上的单个文本重叠
Individual text on Facet plots overlapping
我正在尝试用文本标记构面,但它们在每个构面中都是重叠的,而不是一一显示。这是我一直在使用的代码:
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".
如何让文本标签分别显示在每个方面?
如果您创建用于添加标签的数据框,则该数据还必须有一个用于分面数据的列。以鸢尾花数据集为例:
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")
我个人更喜欢第二种技术,因为您不必担心手动指定坐标。
我正在尝试用文本标记构面,但它们在每个构面中都是重叠的,而不是一一显示。这是我一直在使用的代码:
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".
如何让文本标签分别显示在每个方面?
如果您创建用于添加标签的数据框,则该数据还必须有一个用于分面数据的列。以鸢尾花数据集为例:
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")
我个人更喜欢第二种技术,因为您不必担心手动指定坐标。