2

我想使用 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()
4

2 回答 2

5

看看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)

在此处输入图像描述

于 2020-02-18T09:27:56.123 回答
4

这是一个解决方案geom_arcggforce

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()

在此处输入图像描述

于 2020-02-18T09:54:50.697 回答