剪辑线条以绘制区域并在绘图区域外显示文本 [英] Clip lines to plot area and display text outside plot area
问题描述
我想限制我的情节的可见y范围。为了保留超出此范围的值,我需要将 oob
( out of bounds )设置为 rescale_none code>,这个效果很好。
但是我还想在图的边缘添加一些文字。为了做到这一点,我需要关闭裁剪。这有一个效果,那就是界限外的值被绘制在边界外的绘图区域之外。
是否有利用边距绘制文本和剪辑值来绘制区域?
#Data
set.seed (1)
df < - data.frame(x = 1:100,y = rnorm(100,mean = 1,sd = 1))
#基本图
库(ggplot2)
库(比例)
库(网格)
g< - ggplot(df)+
geom_line(aes(x,y))
#超出比例限制的值将被丢弃
g1 < - g + scale_y_continuous(limits = c(0,2))
p>
#这就是我想要的
g2 < - g + scale_y_continuous(limits = c(0,2),oob = rescale_none)
#...但是,我想要p批量绘图区域以外的一些文本
#并且需要关闭裁剪才能显示文本...
g3 < - g + scale_y_continuous(limits = c(0,2),oob = (aes(label =Nonsense,y = Inf,x = 0),hjust = 0,vjust = -1)+ $ b($ s
$# $ b#为文本添加一些空间
theme(plot.margin = unit(c(2,1,1,1),lines))
#关闭剪辑geom_line也出去绘图区域...
#请参阅这里剪辑... http://stackoverflow.com/a/12417481/1478381
g4 < - ggplot_gtable(ggplot_build(g3))
g4 $ layout $ clip [g4 $ layout $ name ==panel]< - off
grid.draw(g4)
使用
pre $ g $ g $ ggplotGrob(g2 )
gg < - gtable_add_grob(gg,textGrob(Nonsense,x = 0,hjust = 0),t = 1,l = 4)
grid.draw(gg)
I want to restrict the visible y-range of my plot. In order to retain values that fall outside this range I need to set oob
(out of bounds) to rescale_none
and this works well.
However I would also like to add some text in the margins outside the plot. In order to do this I need to turn off clipping. This has the effect that values that are out-of-bounds are plotted outside the plot area in the margins.
Is there anyway to plot text in margins and clip values to plot region?
# 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)
With an approach from here, here's my solution:
library(gtable)
gg <- ggplotGrob(g2)
gg <- gtable_add_grob(gg, textGrob("Nonsense", x=0, hjust=0), t=1, l=4)
grid.draw(gg)
这篇关于剪辑线条以绘制区域并在绘图区域外显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!