我想限制我的情节的可见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)
答案 0 :(得分:4)
使用here的方法,这是我的解决方案:
library(gtable)
gg <- ggplotGrob(g2)
gg <- gtable_add_grob(gg, textGrob("Nonsense", x=0, hjust=0), t=1, l=4)
grid.draw(gg)
答案 1 :(得分:0)
使用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.')