How does one make a portion of label text have strikethrough in a plot label?
For example, to get the y-axis-label to read \"strikethrough text in
You can create a custom element function for axis.text.y
. I tried to get a general solution but I think my solution is a little bit tricky and not very clean since I had to set manually the y position of some viewport(see the code for better explanation)
The custom axis.text.y had 2 arguments : the axis label and the text to strike through it. It finds the position of the text to strike with the axis label and add a segment.(If the text is defined twice it would take only the first occurrence).
To use the solution you can do something like this:
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?"))
the code of the custom axis.text.y element:
# 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")
}