R - 绘图标签文本的文本格式 - 删除线

Eco*_*tis 7 formatting plot text r ggplot2

如何使标签文本的一部分在绘图标签中有删除线?

例如,要使y轴标签读作"标签中的删除线文字? "

 ggplot(mpg, aes(x=displ, y=hwy)) 
        + geom_point() 
        + ylab("~~strikethrough~~ text in a label?")
Run Code Online (Sandbox Code Playgroud)

我认为相当小的问题,找到一个解决方案也是微不足道的,但经过一段时间的寻找后却无济于事.

ags*_*udy 5

您可以为其创建自定义元素功能axis.text.y.我试图得到一个通用的解决方案,但我认为我的解决方案有点棘手而且不是很干净,因为我必须手动设置某个视口的y位置(请参阅代码以获得更好的解释)

自定义axis.text.y有2个参数:轴标签和要通过它的文本.它找到要用轴标签打击的文本的位置并添加一个段.(如果文本定义了两次,则只需要第一次出现).

要使用该解决方案,您可以执行以下操作:

library(ggplot2)
library(grid)
ggplot(mpg, aes(x=displ, y=hwy)) +
    geom_point() + theme(axis.title.y=element_blank())+
    theme( axis.text.y = axis.strike(strike = "label",
               lab="strikethrough text in a label?"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

自定义axis.text.y元素的代码:

# user interface : element called by the user
axis.strike = function(strike,lab) {
    structure(
        list(strike=strike,lab=lab),
        ## inheritance since it should be a element_text
        class = c("element_custom","element_blank")  
    )
}

element_grob.element_custom <- function(element, x,y)  {
    ## the axis label
    g.X <- textGrob(element$lab,rot=90,vjust=-0.25)
    ## I use the grob text dimensions(height,width,position) to 
    ## create a viewport vp
    ## within this viewport I create a segment 
    unit.H <- grobHeight(g.X)
    unit.W <- grobWidth(g.X)
    rate <- nchar(element$strike)
    ## search of the position of the text to strike
    pos <- as.numeric(gregexpr(element$strike,element$lab)[[1]])
    vp=viewport(just="centre",
          ##BAD OFFSET HERE!!
          ## TODO: find better way to define viewport y position
           y = grobY(g.X,'south')+unit(5,'line'), 
           yscale=c(0,nchar(element$lab)),
          width =unit.W,height=unit.H)
    g.seg <- segmentsGrob(vp=vp,x0=0,x1=0,
                           y0=unit(pos-1,'native'),
                           y1=unit(pos-1+rate,'native'))
    gTree(children=gList(g.seg,g.X,g.seg),cl = "custom_axis")
}
Run Code Online (Sandbox Code Playgroud)