ggplot2/grid:保持线段grob箭头相同比例而不考虑长度

d7v8vwbk  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(117)

我使用grid::segmentsGrob(arrow)向ggplot添加箭头。我用x轴坐标定义箭头的位置。出于某种原因,箭头的高度根据箭头的长度进行缩放。我希望箭头占据相同的高度,只缩短箭头的长度。我是否缺少了一个高度参数?

  1. library(ggplot2)
  2. library(grid)
  3. df <- data.frame(
  4. Position=(c(1:5000)),
  5. Signal=(c((rep(c(5),times=2000)), (rep(c(100),times=1000)), (rep(c(5),times=2000))))
  6. )
  7. Plotv1 <- ggplot()+
  8. geom_line(data = df, aes(x=Position, y=Signal, col = "#000000"))+
  9. coord_cartesian(clip="off") +
  10. theme(axis.text.x = element_blank()) +
  11. theme(
  12. axis.title.x = element_text(margin=margin(t=30)),
  13. legend.title = element_text(colour = "#000000", size=12),
  14. legend.text = element_text(colour = "#000000", size=12)
  15. ) +
  16. guides(fill = "none") +
  17. annotation_custom(
  18. grid::segmentsGrob(
  19. y0 = unit(-0.3, "npc"),
  20. y1 = unit(-0.3, "npc"),
  21. arrow = arrow(angle=45, length = unit(.15, 'npc')),
  22. gp = grid::gpar(lwd=3, fill = "#000000")
  23. ),
  24. xmin = 1,
  25. xmax = 1700
  26. ) +
  27. annotation_custom(
  28. grid::segmentsGrob(
  29. y0 = unit(-0.3, "npc"),
  30. y1 = unit(-0.3, "npc"),
  31. arrow = arrow(angle=45, length = unit(.15, 'npc')),
  32. gp = grid::gpar(lwd=3, fill = "#000000")
  33. ),
  34. xmin = 2000,
  35. xmax = 2200
  36. ) +
  37. annotation_custom(
  38. grid::segmentsGrob(
  39. y0 = unit(-0.3, "npc"),
  40. y1 = unit(-0.3, "npc"),
  41. arrow = arrow(angle=45, length = unit(.15, 'npc')),
  42. gp = grid::gpar(lwd=3, fill = "#000000")
  43. ),
  44. xmin = 2500,
  45. xmax = 5000
  46. )
  47. ggsave(paste("~/Desktop/Plotv1.png", sep = ""), Plotv1, width = 8, height = 1.7)

vltsax25

vltsax251#

问题是你指定了箭头的长度,单位是"npc",也就是标准化的父坐标。因此,箭头的长度将随着父视口的绝对宽度和高度的不同而不同,即在您的例子中,每个箭头的视口是由xminxmax定义的矩形。相反,使用绝对单位表示箭头的length。此外,我建议使用绝对单位来定位箭头。

  1. library(ggplot2)
  2. library(grid)
  3. df <- data.frame(
  4. Position = 1:5000,
  5. Signal = c(
  6. rep(5, times = 2000),
  7. rep(100, times = 1000),
  8. rep(5, times = 2000)
  9. )
  10. )
  11. segment <- grid::segmentsGrob(
  12. y0 = unit(-10, "pt"),
  13. y1 = unit(-10, "pt"),
  14. arrow = arrow(angle = 45, length = unit(.3, "cm")),
  15. gp = grid::gpar(lwd = 3, fill = "#000000")
  16. )
  17. ggplot() +
  18. geom_line(data = df, aes(x = Position, y = Signal, col = "#000000")) +
  19. coord_cartesian(clip = "off") +
  20. theme(axis.text.x = element_blank()) +
  21. theme(
  22. axis.title.x = element_text(margin = margin(t = 30)),
  23. legend.title = element_text(colour = "#000000", size = 12),
  24. legend.text = element_text(colour = "#000000", size = 12)
  25. ) +
  26. guides(fill = "none") +
  27. annotation_custom(
  28. segment, xmin = 1, xmax = 1700
  29. ) +
  30. annotation_custom(
  31. segment, xmin = 2000, xmax = 2200
  32. ) +
  33. annotation_custom(
  34. segment, xmin = 2500, xmax = 5000
  35. )

展开查看全部

相关问题