在多个图中添加单独的箭头 [英] Adding individual arrows in multiple plots
问题描述
我想在用ggplot和faceting生成的2个图中添加箭头。问题:如何避免两个图形中箭头的复制?我想添加个别箭头到每个情节。
这里是一个例子:
pre $ library $ g $
$假数据$ b $ (x = rep(1:10,2)
,y = c(2 * c(1:10)+ rnorm(10,0,3),4 * c 1:10)+ rnorm(10,0,5))
,z = rep(c(A,B),each = 10)
)
xdf
#ggplot with faceting
xp< - ggplot(xdf,aes(x = x,y = y))+
geom_line()+
facet_grid(。〜 z)
xp
#箭头的位置:x = 4,y =在顶部
(f1x4 < - xdf [4,y ])+ 1
xp + geom_segment(aes(x = 4,xend = 4,y = f1x4 + 3,yend = f1x4)
,arrow =箭头(长度=单位(0.4,cm )
)
)+
geom_text(aes(x = 4,y = f1x4 + 5,label =a))
pre>
发生了什么:
箭头位于同一区域的两个面内。我怎么能选择一个特定的阴谋放置箭头?
据我可以告诉,要添加个别图层到您需要提供具有相应构面值的数据框。
#如果将多面数据集与缺少这些
#facetting变量的数据集,数据将在缺失的
#组合中重复:
因此,只要做 xp + geom_segment(aes(x,xend,y,yend))
会画出所有方面,因为缺少了构面变量。
您的facetting变量是 z
,所以您可以:
- 使用
x
,<$ c $创建数据框arrow.df
c> y 和z
为'A' - 提供
z
转换为aes
可怕
第二个选项似乎更方便:
xp + geom_segment(aes(x = 4,xend = 4,y = f1x4 + 3,yend = f1x4,z ='A')#< - 见z ='A'
,arrow = arrow(length = unit(0.4,cm)
)
)+
geom_text(aes(x = 4,y = f1x4 + 5,label =a, z ='A'))#< - 见z ='A'
只需在 aes
参数中添加一个 factorvariablename = factor
来在该特定面板上绘图(因为您的<$ c $数据框中的 xp
的级别为'A'和'B')。
I want to add arrows in 2 plots produced with ggplot and faceting. Problem: how can I avoid a replication of the arrow in both graphs? I would like to add individual arrows to each plot. Here is an example:
library(ggplot2)
# data frame with fake data
xdf <- data.frame(x=rep(1:10,2)
,y=c( 2*c(1:10)+rnorm(10,0,3), 4*c(1:10)+rnorm(10,0,5))
,z=rep(c("A","B"),each=10)
)
xdf
# ggplot with faceting
xp <- ggplot(xdf,aes(x=x,y=y)) +
geom_line() +
facet_grid(. ~ z)
xp
# location of the arrow: x=4, y= on the top
(f1x4 <- xdf[4,"y"])+1
xp + geom_segment(aes(x=4,xend=4,y=f1x4+3,yend=f1x4)
, arrow=arrow(length=unit(0.4,"cm")
)
) +
geom_text(aes(x=4,y=f1x4+5, label="a"))
What happened: arrow is placed in both facets in the identical region. How can I choose a specific plot to place the arrows?
As far as I can tell, to add individual layers onto a facet, you need to supply a data frame with the corresponding facet value.
From the ggplot2 facet_grid page:
# If you combine a facetted dataset with a dataset that lacks those
# facetting variables, the data will be repeated across the missing
# combinations:
So just doing xp + geom_segment(aes(x,xend,y,yend))
will draw on all facets, because the facetting variable is missing.
Your facetting variable is z
, so you can either:
- create a dataframe
arrow.df
withx
,y
, andz
being 'A' - feed the
z
intoaes
directly.
Second option seems handier:
xp + geom_segment(aes(x=4,xend=4,y=f1x4+3,yend=f1x4,z='A') # <-- see the z='A'
, arrow=arrow(length=unit(0.4,"cm")
)
) +
geom_text(aes(x=4,y=f1x4+5, label="a",z='A')) # <-- see the z='A'
So you just add in a factorvariablename=factor
to the aes
argument to plot on that particular panel (since your z
column in the data frame for xp
has levels 'A' and 'B').
这篇关于在多个图中添加单独的箭头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!