【问题标题】:Creating space for text annotation to the right of a figure?在图形右侧为文本注释创建空间?
【发布时间】:2021-11-22 12:13:37
【问题描述】:

我正在尝试用一些文本注释我的 ggplot 图,但我很难找到最佳解决方案。我想在图的右侧创建一个边距,以便我可以写课程 A、课程 B 和课程 C。现在我没有足够的空间。我曾尝试使用 plot.margin = unit(c(1,4,1 ,1), "cm") 但这似乎并没有给我可以用来注释情节的空间。 ggplot中有没有可以使用的函数?

trainingplot <- ggplot(aggreg.data, aes(x = trainingblock, y = performance)) +
  scale_y_continuous(name = "Time substracted from straight gliding time (sec.)", breaks = seq(-2, 6, 1)) +
  scale_x_discrete() +
  theme_pubr()+
  theme(legend.position="none",
       axis.title.x=element_blank(),
       plot.margin = unit(c(1,4,1 ,1), "cm")) +
  geom_hline(aes(yintercept = 0), linetype = "dashed", size=0.2) +
  annotate("text", x = 5.4, y = -0.4, label = "Course A", size=4) + 
  annotate("text", x = 5.4, y = 0.5, label = "Course B", size=4) +
  annotate("text", x = 5.4, y = 2, label = "Course C", size=4) 
  

【问题讨论】:

  • 试试+ coord_cartesian(clip = "off")。另一种选择是使用例如增加规模的扩展。 scale_x_discrete(expand = expansion(add = c(.6, 1.2),其中.6 是应用于离散比例的默认扩展。
  • 谢谢。那行得通。 1.2 指的是什么?
  • 默认情况下,ggplot2 将离散比例扩展为两侧的.6 单位,其中1 的单位是两个类别之间的距离。因此1.2 只是默认扩展的两倍,即c(.6, 1.2) 我们将默认扩展保留在左侧,但在右侧加倍。
  • 谢谢。非常有价值的信息。

标签: r ggplot2 cowplot patchwork


【解决方案1】:

对于连续比例,您可以使用辅助轴来注释边距中的特定点。以下标准数据集示例:

library(ggplot2)

ggplot(economics, aes(date)) +
  geom_line(aes(y = unemploy)) +
  scale_y_continuous(
    sec.axis = dup_axis(
      breaks = tail(economics$unemploy, 1),
      labels = "Unemployment", name = NULL
    )
  ) +
  theme(axis.ticks.y.right = element_blank())

reprex package 创建于 2021-09-30 (v2.0.1)

【讨论】:

    猜你喜欢
    • 2021-02-17
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多