【问题标题】:Annotate ggplot2 across both axis: text keeps changing position在两个轴上注释 ggplot2:文本不断改变位置
【发布时间】:2021-02-15 15:11:24
【问题描述】:

我正在尝试用一些文本来注释我的绘图的两个轴,但是当我这样做时,我无法按照我的意愿定位文本。通过在一个轴上添加新文本,另一个轴上的文本会错位。

如何处理?

下面是一个例子来说明我的问题:


set.seed(1234)
x <- rnorm(50, 5, 2)
y <- x + 1 + rnorm(50)
data <- cbind.data.frame(x,y)

#Create a plot in which I annotate in one axis (it works great)

plot <- ggplot(data = data, aes(x, y))+ 
  geom_point() +
  geom_hline(yintercept=median(data$x, na.rm = T), color = 'red') +
  geom_vline(xintercept=median(data$y, na.rm = T), color = 'red') +
  labs(y="Label y", x = "Label x") +
  geom_smooth(method=lm, na.rm = TRUE, fullrange= TRUE,
              aes(group=1),colour="black") +
  theme_bw() +
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 30, b = 0, l = 0))) +
  theme(axis.title.x = element_text(margin = margin(t = 30, r = 0, b = 0, l = 0))) +
  annotate("text", x = 9, y = -3, label = "Helpful Text2") +
  annotate("text", x = 0.5, y = -3, label = "Helpful Text1") +
  coord_cartesian(ylim = c(0, 15), clip = "off")

#Trying to add annotation to the second axis (it alters the axis of the plot, thereby misplacing the annotation I have done prior)
plot + annotate("text", x = 0, y = 8.5, label = "Helpful Text3", angle = 90) +
  annotate("text", x = 0, y = 2, label = "Helpful Text4", angle = 90) +
  coord_cartesian(xlim = c(1, 9), clip = "off")

想法?

【问题讨论】:

  • 不是添加文字改变了位置,而是你第二次改变了你的坐标。由于您的注释是根据绘图的坐标系绘制的,因此当您更改坐标时,您的文本将“移动”。如果您希望第一个文本留在原处,请删除第二个 coord_cartesian 调用。
  • 问题是,如果我这样做,我不能将 y 轴上的文本放在情节之外。换句话说,如果我将这个添加到情节中,我仍然有一个问题: plot + annotate("text", x = 0, y = 12, label = "Helpful Text3", angle = 90) + annotate("text ", x = 0, y = 3, label = "Helpful Text4", angle = 90)

标签: r ggplot2 annotate


【解决方案1】:

你可以试试:

plot + annotate("text", x = -1, y = 14, label = "Helpful Text3", angle = 90) +
  annotate("text", x = -1, y = 0, label = "Helpful Text4", angle = 90) +
  coord_cartesian(ylim = c(0, 15), xlim = c(0, 10), clip = "off")

只需确保在定义情节时将fullrange = FALSE 设置为geom_smooth

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多