Question

I am using ggplot/R for report generation and want more fine-grained control over text formatting.

It's trivial to write some text, apply global formatting parameters, and output to a grid-graphics compatible object - just use textGrob.

t <- textGrob(
  label = "SOME TEXT"
 ,gp=gpar(fontsize=20, col="grey")
)

print(arrangeGrob(t))

Problem is that those formatting options only apply to the entire text string. What I'm looking for is something that would offer basic inline formatting options (font size, bold, italic, etc) - ideally something lightweight like Markdown/CSS/HTML. If I have to learn LaTeX, so be it, but that seems like overkill for what I'm trying to accomplish here.

Any thoughts?

Was it helpful?

Solution

You can use a "text cursor" alongside grid's functions for interrogating grobs. Say you had the phrase: "I want this text bold!!!!!!!, and you want the exclamation points in red:

grid.text("I want ", 
          name="notboldtext",
          hjust=0)  

text.cursor<-convertWidth(grobWidth("notboldtext") # Adds textGrob width & to location
              + unit(.5, "npc"), "npc")           

grid.text("this text bold",
          x=text.cursor, 
          gp=gpar(fontface="bold"),
          name="boldedtext",
          hjust=0)


text.cursor<- text.cursor + convertWidth(grobWidth("boldedtext"), "npc")

grid.text("!!!!!!!", 
          gp=gpar(col="red"),
          x=text.cursor,
          name="maptextnat", 
          hjust=0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top