我使用 grid::segmentsGrob(arrow) 将箭头添加到我的 ggplot 中。我用 x 轴坐标定义箭头的位置。由于某种原因,箭头的高度根据箭头的长度进行缩放。我希望箭头占据相同的高度,而只是缩短箭头的长度。我是否缺少高度参数?
library(ggplot2)
library(grid)
df <- data.frame(
Position=(c(1:5000)),
Signal=(c((rep(c(5),times=2000)), (rep(c(100),times=1000)), (rep(c(5),times=2000))))
)
Plotv1 <- ggplot()+
geom_line(data = df, aes(x=Position, y=Signal, col = "#000000"))+
coord_cartesian(clip="off") +
theme(axis.text.x = element_blank()) +
theme(
axis.title.x = element_text(margin=margin(t=30)),
legend.title = element_text(colour = "#000000", size=12),
legend.text = element_text(colour = "#000000", size=12)
) +
guides(fill = "none") +
annotation_custom(
grid::segmentsGrob(
y0 = unit(-0.3, "npc"),
y1 = unit(-0.3, "npc"),
arrow = arrow(angle=45, length = unit(.15, 'npc')),
gp = grid::gpar(lwd=3, fill = "#000000")
),
xmin = 1,
xmax = 1700
) +
annotation_custom(
grid::segmentsGrob(
y0 = unit(-0.3, "npc"),
y1 = unit(-0.3, "npc"),
arrow = arrow(angle=45, length = unit(.15, 'npc')),
gp = grid::gpar(lwd=3, fill = "#000000")
),
xmin = 2000,
xmax = 2200
) +
annotation_custom(
grid::segmentsGrob(
y0 = unit(-0.3, "npc"),
y1 = unit(-0.3, "npc"),
arrow = arrow(angle=45, length = unit(.15, 'npc')),
gp = grid::gpar(lwd=3, fill = "#000000")
),
xmin = 2500,
xmax = 5000
)
ggsave(paste("~/Desktop/Plotv1.png", sep = ""), Plotv1, width = 8, height = 1.7)
问题是您以
"npc"
单位(又称标准化父坐标)指定了箭头的长度。因此,随着父视口的绝对宽度和高度不同,箭头的长度也会有所不同,即在您的情况下,每个箭头的视口是由 xmin
和 xmax
定义的矩形。相反,请对箭头的 length
使用绝对单位。此外,我建议也使用绝对单位来定位箭头。
library(ggplot2)
library(grid)
df <- data.frame(
Position = 1:5000,
Signal = c(
rep(5, times = 2000),
rep(100, times = 1000),
rep(5, times = 2000)
)
)
segment <- grid::segmentsGrob(
y0 = unit(-10, "pt"),
y1 = unit(-10, "pt"),
arrow = arrow(angle = 45, length = unit(.15, "cm")),
gp = grid::gpar(lwd = 3, fill = "#000000")
)
ggplot() +
geom_line(data = df, aes(x = Position, y = Signal, col = "#000000")) +
coord_cartesian(clip = "off") +
theme(axis.text.x = element_blank()) +
theme(
axis.title.x = element_text(margin = margin(t = 30)),
legend.title = element_text(colour = "#000000", size = 12),
legend.text = element_text(colour = "#000000", size = 12)
) +
guides(fill = "none") +
annotation_custom(
segment, xmin = 1, xmax = 1700
) +
annotation_custom(
segment, xmin = 2000, xmax = 2200
) +
annotation_custom(
segment, xmin = 2500, xmax = 5000
)