nathaneastwood
nathaneastwood

Reputation: 3764

How to add a math character (lozenge) to a ggplot title

I am trying to add a \lozenge to a ggplot2 title. Some example code would be:

tmp = data.frame(x = rnorm(100), y = rnorm(100))
ggplot(tmp, aes(x, y)) + 
  geom_point() + 
  ggtitle(expression(lozenge))

But I cannot get the lozenge to appear. It simply prints the word lozenge. I also need to be able to change the colour of the lozenge.

Upvotes: 2

Views: 1025

Answers (1)

Cath
Cath

Reputation: 24074

You can try:

ggplot(tmp, aes(x, y)) + 
         geom_point() + 
         ggtitle(bquote(symbol("\340")))

To change its color, you can add a theme argument.
For example, for a red lozenge:

ggplot(tmp, aes(x, y)) + 
            geom_point() +   
            ggtitle(bquote(symbol("\340"))) +  
            theme(plot.title=element_text(color="red"))

with the example: enter image description here

EDIT

If you want to have a bi-color title, following Roland's solution of this question, this is how to do it:

# assign your plot object to a variable
p<-ggplot(tmp, aes(x, y)) + geom_point() + ggtitle(bquote(paste("some text ",symbol("\340")," some more text",sep="")))

# get the "Grob" object
grob_p<- ggplotGrob(p)

# modify the text and text colors. Here, you have to use the hexadecimal code for the lozenge    
grob_p[[1]][[8]]$label<-c("some text ", bquote("\U0025CA"), " some more text")
grob_p[[1]][[8]]$gp$col<-c("black","red","black")

# adjust the coordinates of the different strings
grob_p[[1]][[8]]$x<-unit(c(0.41,0.5,0.63),"npc")

# plot the modified object
plot(grob_p)

enter image description here

Upvotes: 1

Related Questions