如何将数学字符(菱形)添加到ggplot标题中

时间:2015-02-16 12:05:24

标签: r ggplot2 latex

我正在尝试将\lozenge添加到ggplot2标题中。一些示例代码是:

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

但我不能让锭剂出现。它只是打印单词lozenge。我还需要能够改变锭剂的颜色。

1 个答案:

答案 0 :(得分:1)

您可以尝试:

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

要更改颜色,可以添加theme参数 例如,对于红色菱形:

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

以示例: enter image description here

修改

如果您想拥有双色标题,请遵循Roland的this question解决方案,这是如何做到的:

# 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