r - 在ggplot2中创建箭头匹配大小(或lwd)

标签 r ggplot2 plot

为了在 ggplot 中绘制箭头,我使用 geom_segment 和 arrow=arrow()。 我希望箭头大小与线段宽度(或大小)相匹配。 然而,arrow 不能直接从 ggplot 中的 data 参数识别变量,必须使用 $ 运算符指定包含变量的 data.frame。这会导致用于绘制线条的值和用于绘制箭头的值之间出现分离(最大的箭头可以位于最细的线段上)。

示例:

d <- structure(list(Process = structure(c(2L, 1L, 1L, 1L, 2L, 2L, 
1L, 1L, 2L, 1L, 2L), .Label = c("First", "Second"), class = "factor"), 
x.sink = c(1, 3, 1, 2, 2, 3, 3, 2, 2, 2, 2), y.sink = c(1, 
1, 1, 2, 2, 1, 1, 1, 1, 2, 2), x.source = c(2, 2, 2, 2, 2, 
2, 2, 1, 1, 1, 3), y.source = c(2, 2, 2, 1, 1, 1, 1, 1, 1, 
2, 1), offset = c(1, 1, 1, -1, -1, -1, -1, -1, -1, 1, -1), 
Std.Flux = c(0.179487179487179, 0.170940170940171, 0.944444444444444, 
0.0854700854700855, 0.726495726495726, 0.128205128205128, 
0.213675213675214, 0.213675213675214, 0.128205128205128, 
0.106837606837607, 1)), .Names = c("Process", "x.sink", "y.sink", 
"x.source", "y.source", "offset", "Std.Flux"), class = "data.frame", row.names = c(NA, 
-11L))


p <- qplot(data=d,
           #alpha=I(0.4),
           colour=Process,
           size=Std.Flux,
           xlim=c(0,4),
           ylim=c(0,3),
           x=x.source+as.numeric(Process)/10,
           y=y.source+as.numeric(Process)/10,
           xend=x.sink+as.numeric(Process)/10,
           yend=y.sink+as.numeric(Process)/10,
           geom="segment",
           arrow = arrow(type="closed",
                         length = unit(d$Std.Flux,"cm")))
print(p)

Disjunct arrow heads

有什么建议吗?

最佳答案

这是一种方法:

require(ggplot2)

df <- mtcars

arrow_pos <- data.frame(y = 250)

ggplot(df, aes(x=factor(cyl), y=mpg)) +
  geom_bar(width = .4, stat="identity", fill="darkblue")  +
  geom_segment(data=arrow_pos, 
               aes(x=1.526, xend=1.01, y=y + 90.02, yend=y + 0.25),
               arrow=arrow(length=unit(4.2, "mm")), lwd=2,
               color="black") +
  geom_segment(data=arrow_pos, 
               aes(x=1.525, xend=1.01, y=y + 90, yend=y + 0.25),
               arrow=arrow(length=unit(4, "mm")), lwd=1,
               color="gold2") +
  annotate("text", x=2.39, y=360, 
           label='This arrow points to the highest MPG.') +
  scale_y_continuous(limits = c(0,400)) +
  xlab('CYL') + ylab('MPG')

输出:

enter image description here

关于r - 在ggplot2中创建箭头匹配大小(或lwd),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16874922/

相关文章:

python - R: system() 不能使用 .bashrc 中定义的 bash 函数

r - ggplot2 图例与每个其他分组的轮廓

r - ggplot2 绘制两个子集的图形

r - 将 geom_point 覆盖到 geom_bar。如何对齐点和条?

r - 查找相同值的每个子集的最大值

r - 如何正确使用 addResourcePath?

r - ggplot 堆叠条形排序失败,函数 desc 未知

Matlab如何填充箭袋箭头

python - 绘制/转换来自 sympy : Taylor series with matplotlib 的表达式

python - Python 中的方程式