【问题标题】:ggplot, drawing line between points across facetsggplot,在各个方面的点之间画线
【发布时间】:2015-07-29 01:56:51
【问题描述】:

使用 ggplot2,我怎样才能画出一条在分面之间运行的趋势线。

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)

这会产生以下内容:

在上面,我想在三个点之间画一条线,跨越多个方面。

【问题讨论】:

  • 提供一些上下文可能会很有用,说明为什么在图形之间延伸一条线会很有用,尽管 x 值有中断。实现这一点的一种方法 - 尽管需要手动调整 - 将添加与下一个面板上第一个点的位置匹配的视场外(即 x 轴限制之外)的点。
  • 哈哈..library(df),对此感到抱歉....
  • @PhilippeMarchand 在我正在写的一篇论文中描述三种实验配置之间的一般行为。
  • 为什么它们会出现在不同的面板上,它们之间的线没有意义,因为 x 范围重置
  • 它不是“线性回归”线,我希望它能够说明三个实验条件之间的现象。就我而言,每个面板的 x 范围都是相同的。

标签: r ggplot2


【解决方案1】:

更新到ggplot2 V3.0.0

您可以这样做,但关闭剪辑可能会产生不良后果,

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(.01,.99),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)
library(grid)
# 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_params
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 = 8, l = 5)
# draw line to end position in last panel
g <- gtable_add_grob(g, lineToGrob(end[1],end[2]), 
                     t = 8, l = 9, z=Inf)
# turn clip off to see the line across panels
g$layout$clip <- "off"
grid.newpage()
grid.draw(g)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
相关资源
最近更新 更多