繁体   English   中英

剪切线以绘制区域并在绘图区域外显示文本

[英]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) )

OOB值下降

#  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)

在此输入图像描述

这里开始 ,这是我的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM