简体   繁体   English

r - 将geom_segment与coord_polar一起使用

[英]r - Using geom_segment with coord_polar

I want to do something similar to the answer in this post , but with geom_segment() instead of geom_path() because now I want to add arrows to my lines. 我想做一些类似于这篇文章中的答案,但是使用geom_segment()而不是geom_path()因为现在我想在我的行中添加箭头。

Setup: 建立:

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

在此输入图像描述

I want a plot that looks like this, but with arrows in the direction of the next point in the sequence. 我想要一个看起来像这样的情节,但箭头指向序列中下一个点的方向。

These are my attempts: 这些是我的尝试:

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

在此输入图像描述

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

在此输入图像描述

Well, this solution is even hackier than the answer to your first question. 嗯,这个解决方案甚至比第一个问题的答案还要糟糕 Instead of using geom_segment I use geom_path , but this will produce only the last arrow, so we will add the group aesthetic to connect segments one by one. 而不是使用的geom_segment我用geom_path ,但这会产生只有最后一个箭头,所以我们将添加group唯美的一对一的连接段。 This means our original data frame has to be slightly modified: 这意味着我们的原始数据框架必须稍加修改:

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

在此输入图像描述

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

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