繁体   English   中英

ggplot2 绘制两条线之间的角度

[英]ggplot2 plot an angle between two lines

我想使用 ggplot2 绘制两条线之间的角度,这意味着类似于下图中的粗体红线。 有没有简单的解决方案?

plot_with_red_line

制作没有红线的图的数据和代码:

library(tidyverse)

df <- tibble(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5))

ggplot(
  df, aes(x, y, group = line))+
  geom_path()

看看geom_curve ,例如:

ggplot(  df, aes(x, y, group = line))+
  geom_path() +
  geom_curve(aes(x = 1.5, y = 2, xend = 2, yend = 1.5), curvature = -0.5, color = "red", size = 3)

在此处输入图片说明

您必须稍微调整一下才能以更强大、更自动的方式使用它,例如:

red_curve <- df %>%
  group_by(line) %>%
  summarise( avg_x = mean(x),
             avg_y = mean(y))

ggplot(  df, aes(x, y, group = line))+
  geom_path() +
  geom_curve( data = red_curve, aes(x = avg_x[1], y = avg_y[1], xend = avg_x[2], yend = avg_y[2]), curvature = 0.5, color = "red", size = 3)

在此处输入图片说明

这里是用溶液geom_arc所述的ggforce包。

library(ggplot2)
library(ggforce)

angle <- function(p, c){
  M <- p - c
  Arg(complex(real = M[1], imaginary = M[2]))
}

O <- c(1,1)
P1 <- c(5,3)
P2 <- c(3,5)
a1 <- angle(P1, O)
a2 <- angle(P2, O)

df <- data.frame(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5)
)

ggplot(df, aes(x, y, group = line)) +
  geom_path() + 
  geom_arc(aes(x0 = 1, y0 = 1, r = 1, start = a1, end = a2), 
           color="red", size = 2, inherit.aes = FALSE)

在此处输入图片说明

圆弧看起来不像真正的圆弧圆。 那是因为纵横比未设置为 1。要将纵横比设置为 1:

ggplot(df, aes(x, y, group = line)) +
  geom_path() + 
  geom_arc(aes(x0 = 1, y0 = 1, r = 1, start = a1, end = a2), 
           color="red", size = 2, inherit.aes = FALSE) + 
  coord_fixed()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM