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

5
我希望限制绘图的可见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) )

OOB values dropped

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

enter image description here

#  ...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... https://dev59.com/I2ct5IYBdhLWcg3wApCH#12417481
g4 <- ggplot_gtable(ggplot_build(g3))
g4$layout$clip[g4$layout$name == "panel"] <- "off"

grid.draw(g4)

enter image description here


不使用coord_cartesian和clipping可以实现这个吗? - rawr
@rawr 不行。同样的问题。 - Simon O'Hanlon
1
嗯,我做过类似的事情就是创建另一个只有文本的图形,然后将两个图形堆叠在一起。我相信那位巫师@baptiste会知道更好的方法。 - rawr
2个回答

4

参考这里的方法,这是我的解决方案:

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

enter image description here


我遇到了相同的问题,只是我的“胡说八道”必须在中间,我通过改变t和l的值找到了解决方法。然而,我需要它以不同的颜色显示,与原始标题不同!!这就是困扰我的地方。 - zazu

0

使用ggplot2::labs()。最新版本的ggplot2包含了这个函数,可以在每个图表上打印标题、副标题和说明。

p = ggplot(mtcars, aes(mpg, wt, colour = cyl)) + geom_point() p + labs(colour = "汽缸") p + labs(x = "新的x标签", title='绘图标题', caption='来源:国际货币基金组织。')

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接