ggplot,绘制各个面之间的点 [英] ggplot, drawing line between points across facets

查看:127
本文介绍了ggplot,绘制各个面之间的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ggplot2,我该如何绘制一个在各个方面之间运行的趋势线。

Using ggplot2, how can I draw a trendline which runs between facets.

library(ggplot2)
df <- data.frame(y=c(1,2,3),x=1,Set=LETTERS[1:3])
ggplot(df,aes(x,y)) + 
  theme_bw() + theme(legend.position=c(0,1),legend.justification=c(0,1)) + 
  geom_point(aes(fill=Set),color="black",shape=21,size=3) + 
  facet_grid(~Set) + 
  xlim(1,5)

其中产生以下内容:

在上面,我想在这三点之间划一条线,穿过各个方面。

In the above, I would like to draw a line between the three points, moving across facets.

推荐答案

您可以这样做,但关闭剪辑可能会带来不必要的后果,

You could do this, but turning clip off might have unwanted consequences,

library(ggplot2)
df <- data.frame(y=c(1,2,3),x=1,Set=LETTERS[1:3])
p <- ggplot(df,aes(x,y)) + 
  theme_bw() + theme(legend.position=c(0,1),legend.justification=c(0,1)) + 
  geom_point(aes(fill=Set),color="black",shape=21,size=3) + 
  facet_grid(~Set) + 
  xlim(1,5) 

gb <- ggplot_build(p)
g <- ggplot_gtable(gb)

library(gtable)
# ggplot2 doesn't use native units in data space
# instead, the data is rescaled to npc, i.e from 0 to 1
# so we need to use the build info to convert from data to [0,1]
ranges <- gb$layout$panel_ranges
data2npc <- function(x, range) scales::rescale(c(range, x), c(0,1))[-c(1,2)]

start <- c(data2npc(1, ranges[[1]][["x.range"]]), 
           data2npc(1, ranges[[1]][["y.range"]]))

end <- c(data2npc(1, ranges[[3]][["x.range"]]), 
           data2npc(3, ranges[[3]][["y.range"]]))
# starting position in the first panel
g <- gtable_add_grob(g, moveToGrob(start[1],start[2]), 
                     t = 7, l = 4)
# draw line to end position in last panel
g <- gtable_add_grob(g, lineToGrob(end[1],end[2]), 
                     t = 7, l = 8, r=8, z=Inf)
# turn clip off to see the line across panels
g$layout$clip <- "off"
grid.newpage()
grid.draw(g)

这篇关于ggplot,绘制各个面之间的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆