ggplot中的两个散点图,两个散点图之间带有箭头

时间:2014-02-20 06:02:48

标签: r ggplot2

我知道可以put two scatterplots onto one plot in ggplot2,但我还需要在相关点之间加上箭头。

例如,如果我有以下data.frame

SPEAKER <- c("A","A","B","B")
VOWEL <- c("ej","ow","ej","ow")
MB_F1_ONGLIDE <- c(423.88,533.297,465.796,532.118)
MB_F2_ONGLIDE <- c(1847.428,962.485,1815.381,1058.883)
MB_F1_OFFGLIDE <- c(404.827,480.176,423.381,522.727)
MB_F2_OFFGLIDE <- c(1885.349,911.669,1887.392,971.168)
data <- data.frame(SPEAKER,VOWEL,MB_F1_ONGLIDE,MB_F2_ONGLIDE,MB_F1_OFFGLIDE,MB_F2_OFFGLIDE)

我知道我可以在同一个地块上出现两个散点图:

plot <- ggplot(data,aes(x = MB_F2_ONGLIDE,y = MB_F1_ONGLIDE,color = SPEAKER,label = VOWEL)) +
    geom_text(aes(x = MB_F2_ONGLIDE,y = MB_F1_ONGLIDE)) + 
    geom_text(aes(x = MB_F2_OFFGLIDE,y = MB_F1_OFFGLIDE)) +
    scale_x_reverse() +
    scale_y_reverse()

产生:

enter image description here

但我想要的是:

enter image description here

也就是说,我希望能够绘制从MB_F1_ONGLIDE值到MB_F1_OFFGLIDE值的箭头以及从MB_F2_ONGLIDE值到MB_F2_OFFGLIDE的箭头的内容值。

这可能吗?

1 个答案:

答案 0 :(得分:4)

是的 - 您可以使用geom_segment(),您需要加载gridgridExtra来绘制箭头。您可以在geom_segment调用中修改线条大小/颜色,查看?箭头以了解如何更改箭头形状/行为

require(gridExtra)

ggplot(data,aes(x = MB_F2_ONGLIDE,y = MB_F1_ONGLIDE,color = SPEAKER,label = VOWEL)) +
  geom_text(aes(x = MB_F2_ONGLIDE,y = MB_F1_ONGLIDE)) + 
  geom_text(aes(x = MB_F2_OFFGLIDE,y = MB_F1_OFFGLIDE)) +
  geom_segment(aes(x = MB_F2_ONGLIDE,y = MB_F1_ONGLIDE,xend = MB_F2_OFFGLIDE,yend = MB_F1_OFFGLIDE,color=SPEAKER),arrow=arrow()) +
  scale_x_reverse() +
  scale_y_reverse()

enter image description here