【问题标题】:Clip lines to plot area and display text outside plot area将线条剪切到绘图区域并在绘图区域外显示文本
【发布时间】:2015-03-12 11:45:34
【问题描述】:

我想限制绘图的可见 y 范围。为了保留超出此范围的值,我需要将oob超出范围)设置为rescale_none,这样效果很好。

不过,我还想在绘图外的空白处添加一些文本。为了做到这一点,我需要关闭剪辑。这会导致超出边界的值被绘制在绘图区域之外的边距中。

是否可以在边距中绘制文本剪辑值以绘制区域?

#  Data
set.seed(1)
df <- data.frame( x=1:100,y=rnorm(100,mean=1,sd=1) )
# Basic plot

library(ggplot2)
library(scales)
library(grid)

g <- ggplot(df)+
geom_line(aes(x,y))


#  Values exceeding scale limits are dropped
g1 <- g + scale_y_continuous( limits = c(0,2) )

#  This is what I want
g2 <- g + scale_y_continuous( limits = c(0,2) , oob = rescale_none )

#  ...But, I would like to plot some text outside the plotting region
#  and need to turn off clipping to get the text to display...
g3 <- g + scale_y_continuous( limits = c(0,2) , oob = rescale_none ) +
    # Some text to sit above the plot
    geom_text( aes(label = "Nonsense", y = Inf, x = 0), hjust = 0, vjust = -1) +
    # Add some space for the text
    theme(plot.margin = unit(c(2,1,1,1), "lines")) 

#  Turning off clipping makes geom_line also go outside plot area...
#  See here for clipping... http://stackoverflow.com/a/12417481/1478381
g4 <- ggplot_gtable(ggplot_build(g3))
g4$layout$clip[g4$layout$name == "panel"] <- "off"

grid.draw(g4)

【问题讨论】:

  • coord_cartesian + clipping 不这样做
  • @rawr 没有。同样的问题。
  • hm,我所做的唯一另一件事是创建另一个仅包含文本的绘图并将两者堆叠在一起。我相信巫师@baptiste 会知道一些事情

标签: r graphics plot ggplot2


【解决方案1】:

使用here 的方法,这是我的解决方案:

library(gtable)
gg <- ggplotGrob(g2)
gg <- gtable_add_grob(gg, textGrob("Nonsense", x=0, hjust=0), t=1, l=4)
grid.draw(gg)

【讨论】:

  • 我遇到了同样的问题,除了我的“废话”必须在中间,我发现通过改变 t 和 l 值。但是我需要它与原始标题不同的颜色!!这就是让我困惑的地方
【解决方案2】:

使用ggplot2::labs()。 ggplot2 的最新版本包含此功能,可在每个图形上打印标题、副标题和说明。

p = ggplot(mtcars, aes(mpg, wt, colour = cyl)) + geom_point() p + labs(colour = "Cylinders") p + labs(x = "New x label", title='Plot title', caption='Source: IMF.')

来源:https://github.com/tidyverse/ggplot2/pull/1582

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2023-03-22
    • 1970-01-01
    • 2013-06-18
    • 2015-11-10
    相关资源
    最近更新 更多