将线剪裁到绘图区域并在绘图区域外显示文本

Clip lines to plot area and display text outside plot area

我想限制绘图的可见 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... 
g4 <- ggplot_gtable(ggplot_build(g3))
g4$layout$clip[g4$layout$name == "panel"] <- "off"

grid.draw(g4)

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

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

使用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