在 ggplot2 中自定义线型或在行下方添加自动 arrows/symbols
Customize linetype in ggplot2 OR add automatic arrows/symbols below a line
我想在 ggplot 中使用自定义线型。如果那是不可能的(我相信这是真的),那么我正在寻找一个聪明的黑客来在我的线上方或下方绘制类似箭头的符号。
一些背景:
我想绘制一些水质数据并将其与红线中的标准(由欧洲水框架指令设定)进行比较。这是一些可重现的数据和我的情节:
df <- data.frame(datum <- seq.Date(as.Date("2014-01-01"),
as.Date("2014-12-31"),by = "week"),y=rnorm(53,mean=100,sd=40))
(plot1 <-
ggplot(df, aes(x=datum,y=y)) +
geom_line() +
geom_point() +
theme_classic()+
geom_hline(aes(yintercept=70),colour="red"))
但是,在此图中,完全不清楚标准是最大值(例如氯化物)还是最小值(例如氧气)。所以我想通过添加 small pointers/arrows Up 或 Down 来明确这一点。最好的方法是自定义线型,使其由这些箭头组成,但我找不到办法。
Q1:这完全可能吗,定义自定义线型?
我能想到的就是在线下添加额外的点:
extrapoints <- data.frame(datum2 <- seq.Date(as.Date("2014-01-01"),
as.Date("2014-12-31"),by = "week"),y2=68)
plot1 + geom_point(data=extrapoints, aes(x=datum2,y=y2),
shape=">",size=5,colour="red",rotate=90)
但是,我似乎无法旋转这些指向下方的符号。此外,这需要每次都计算正确的X间距和到线(Y)的距离,这是相当不方便的。
Q2:有没有什么办法可以实现,最好是尽可能自动化?
我不确定请求的是什么,但听起来好像您希望根据 y 值大于或小于某个预期值的位置向上或向下箭头。如果是这样的话,那么这满足使用 geom_segment
:
require(grid) # as noted by ?geom_segment
(plot1 <-
ggplot(df, aes(x=datum,y=y)) + geom_line()+
geom_segment(data = data.frame( df$datum, y= 70, up=df$y >70),
aes(xend = datum , yend =70 + c(-1,1)[1+up]*5), #select up/down based on 'up'
arrow = arrow(length = unit(0.1,"cm"))
) + # adjust units to modify size or arrow-heads
geom_point() +
theme_classic()+
geom_hline(aes(yintercept=70),colour="red"))
如果我对所需内容的理解有误,而您只想要一堆向下箭头,那么只需删除有关创建和使用 "up" 的内容并使用减号即可。
我想在 ggplot 中使用自定义线型。如果那是不可能的(我相信这是真的),那么我正在寻找一个聪明的黑客来在我的线上方或下方绘制类似箭头的符号。
一些背景:
我想绘制一些水质数据并将其与红线中的标准(由欧洲水框架指令设定)进行比较。这是一些可重现的数据和我的情节:
df <- data.frame(datum <- seq.Date(as.Date("2014-01-01"),
as.Date("2014-12-31"),by = "week"),y=rnorm(53,mean=100,sd=40))
(plot1 <-
ggplot(df, aes(x=datum,y=y)) +
geom_line() +
geom_point() +
theme_classic()+
geom_hline(aes(yintercept=70),colour="red"))
但是,在此图中,完全不清楚标准是最大值(例如氯化物)还是最小值(例如氧气)。所以我想通过添加 small pointers/arrows Up 或 Down 来明确这一点。最好的方法是自定义线型,使其由这些箭头组成,但我找不到办法。
Q1:这完全可能吗,定义自定义线型?
我能想到的就是在线下添加额外的点:
extrapoints <- data.frame(datum2 <- seq.Date(as.Date("2014-01-01"),
as.Date("2014-12-31"),by = "week"),y2=68)
plot1 + geom_point(data=extrapoints, aes(x=datum2,y=y2),
shape=">",size=5,colour="red",rotate=90)
但是,我似乎无法旋转这些指向下方的符号。此外,这需要每次都计算正确的X间距和到线(Y)的距离,这是相当不方便的。 Q2:有没有什么办法可以实现,最好是尽可能自动化?
我不确定请求的是什么,但听起来好像您希望根据 y 值大于或小于某个预期值的位置向上或向下箭头。如果是这样的话,那么这满足使用 geom_segment
:
require(grid) # as noted by ?geom_segment
(plot1 <-
ggplot(df, aes(x=datum,y=y)) + geom_line()+
geom_segment(data = data.frame( df$datum, y= 70, up=df$y >70),
aes(xend = datum , yend =70 + c(-1,1)[1+up]*5), #select up/down based on 'up'
arrow = arrow(length = unit(0.1,"cm"))
) + # adjust units to modify size or arrow-heads
geom_point() +
theme_classic()+
geom_hline(aes(yintercept=70),colour="red"))
如果我对所需内容的理解有误,而您只想要一堆向下箭头,那么只需删除有关创建和使用 "up" 的内容并使用减号即可。