【发布时间】: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 会知道一些事情