【问题标题】:R - Text Formatting of Plot Label Text - StrikethroughR - 绘图标签文本的文本格式 - 删除线
【发布时间】:2013-12-17 10:23:34
【问题描述】:

如何使标签文本的一部分在情节标签中带有删除线?

例如,要让y轴标签读取“删除线标签中的文本?

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

非常小的问题,我认为找到解决方案也很简单,但经过一段时间的查找无济于事。

【问题讨论】:

  • ?element_text 不是一个选项,所以我认为这不是一个选项?

标签: r text plot formatting ggplot2


【解决方案1】:

您可以为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?"))

自定义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")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-16
    • 2020-07-08
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    相关资源
    最近更新 更多