如何通过ggplot2在笛卡尔坐标系中绘制矢量?

时间:2019-01-22 13:51:13

标签: r ggplot2

我想绘制一个点P(2,4)和点Q(-4,-6)的向量。我可以在基本绘图系统中轻松编写此代码。

arrows(0, 0, 2, 4, angle=20) # command to draw vector as arrows. 
arrows(0, 0, -4, -6, angle=20) # with angle of the arrow

但是,当我要将其转换为ggplot2时,我不知道如何继续。

x1 <- c(0,2,-4)
y1 <- c(0,4,-6)
df <- data.frame(x1,y1)

ggplot(df) + 
    geom_point(aes(x = x1, y = y1))

2 个答案:

答案 0 :(得分:1)

您将要使用geom_segment而不是geom_point

library(ggplot2)
ggplot() + 
  geom_segment(aes(x = 0, y = 0, xend = 2, yend = 4)) + 
  geom_segment(aes(x = 0, y = 0, xend = -4, yend = -6))

enter image description here

答案 1 :(得分:0)

这是尝试:

      library(tidyverse)
      x=c(-6:6)
      y=c(-6:6)
      df %>% 
  ggplot(aes(x,y))+geom_abline(aes(slope=0,intercept=0))+
  annotate("text",x=2,y=4,label="P",size=9,colour="red")+
  annotate("text",x=-4,y=-6,label="Q",colour="red",size=9)+
  geom_vline(xintercept = 0)+
  geom_point(aes(x=0,y=0))+
  geom_segment(aes(x=0,y=0,xend=2,yend=4),
               arrow=arrow(length = unit(0.5,"cm"),angle=20),lineend = "butt")+
  geom_segment(aes(x=0,y=0,xend=-4,yend=-6),
               arrow=arrow(length = unit(0.5,"cm"),angle=20),lineend = "butt",linejoin = "round")+
  theme_minimal()

图: enter image description here