r - 将 geom_segment 与 coord_pol 一起使用

标签 r ggplot2 lines polar-coordinates

我想做一些类似于此post中的答案的事情,但使用 geom_segment() 而不是 geom_path() 因为现在我想向我的线条添加箭头。

设置:

example <- data.frame(r=c(5,4,3),theta=c(0.9,1.1,0.6))

is.linear.polar2 <- function(x) TRUE
coord_polar2 <- coord_polar(theta="y", start = 3/2*pi, direction=-1) 
class(coord_polar2) <- c("polar2", class(coord_polar2))

myplot <- ggplot(example, aes(r, theta)) + geom_point(size=3.5) +
  scale_x_continuous(breaks=seq(0,max(example$r)), lim=c(0, max(example$r))) + 
  scale_y_continuous(breaks=round(seq(0, 2*pi, by=pi/4),2), expand=c(0,0), lim=c(0,2*pi)) +
  geom_text(aes(label=rownames(example)), size=4.4, hjust=0.5, vjust=-1)

myplot + coord_polar2 + geom_path()

enter image description here

我想要一个看起来像这样的图,但箭头指向序列中下一个点的方向。

这些是我的尝试:

myplot + coord_polar2 + 
geom_segment(data=example,aes(x=r, y=theta, xend=c(tail(r, n=-1), NA), 
                              yend=c(tail(theta, n=-1), NA)),
             arrow=arrow(length=unit(0.3,"cm"), type="closed"))

enter image description here

myplot + coord_polar(theta="y", start = 3/2*pi, direction=-1) + 
geom_segment(data=example,aes(x=r, y=theta, xend=c(tail(r, n=-1), NA), 
                              yend=c(tail(theta, n=-1), NA)),
             arrow=arrow(length=unit(0.3,"cm"), type="closed"))

enter image description here

最佳答案

嗯,这个解决方案比你第一个问题的答案还要更黑客。我没有使用geom_segment,而是使用geom_path,但这只会产生最后一个箭头,因此我们将添加group美感来逐个连接段一。这意味着我们的原始数据框必须稍微修改:

tweak_data <- function(df) 
{
  if (nrow(df) == 1) return(df)
  idx_x2 <- c(1, rep(2:(nrow(df) - 1), each=2), nrow(df))
  gr <- rep(seq.int(nrow(df) - 1), each=2)
  df_res <- data.frame(r = df$r[idx_x2], theta = df$theta[idx_x2], 
                       label = rownames(df)[idx_x2], group = gr)
  df_res
}

example_tw <- tweak_data(example)
myplot2 <- ggplot(example2, aes(r, theta)) + geom_point(size=3.5) +
  scale_x_continuous(breaks=seq(0,max(example$r)), lim=c(0, max(example$r))) + 
  scale_y_continuous(breaks=round(seq(0, 2*pi, by=pi/4), 2), 
                     expand=c(0, 0), lim=c(0, 2*pi)) +
  geom_text(aes(label=label), size=4.4, hjust=0.5, vjust=-1)
myplot2 + coord_polar2 + 
  geom_path(aes(group=group), arrow=arrow(length=unit(0.3,"cm"), type="closed"))

enter image description here

关于r - 将 geom_segment 与 coord_pol 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726609/

相关文章:

reporting-services - 使用不同的线条样式而不是颜色

python - Pandas 能否在没有迭代的情况下找到连接任何一对**点**并且不与任何给定的**线**相交的所有线?

r - 控制ggplot2图异常(exception)观而不影响绘图

r - 将 tidymodels 配方包装到函数中

r - 如何避免data.table中的冗余计算?

r - 在R中使用foreach将内存使用量加倍

r - 按组连接躲避的 geom_point 的点

r - 使用 ggplot2 直接绘制 ts 对象

ios - 在 iOS 中以编程方式绘制多条线

r - 将标题添加到由 "write.csv"创建的文件