Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add latex expression on x-axis ticks @ggplot2

I have this data frame :

library(ggplot2)
library('latex2exp')

dfvi<-structure(list(rel.imp = c(7.97309042736285, 3.68859054679465, 
-0.672404901177933, -0.56914400358685, 0.461768686793877,-0.393707520847751, 
0.331273538653149, 0.257999910761084, -0.226891321033094, 0.179124365066449
), x.names = c("a", "x", "d", "ft", "ew", "qw", "ccc", "sas", 
"imb", "msf")), row.names = c(NA, -10L), .Names = c("rel.imp", 
"x.names"), class = "data.frame")

I do a plot as follows using ggplot2:

ggplot(dfvi, aes(x=x.names, y=rel.imp)) +
geom_segment( aes(x=x.names, xend=x.names, y=0, yend=rel.imp),color="grey") +
geom_point( color="orange", size=4) +
scale_y_continuous(breaks=c(-1,seq(0,8,2)))+
scale_x_discrete(labels=c('a'='a','x'='x','d'=TeX('$mode(L_{ij})$'),'ft'=expression('$R_{ij}$'),'ew'=TeX('$Q_{ij}$'),'qw'='qw','ccc'='ccc','sas'='sas','imb'='imb','msf'='msfff'))+
theme_light() + 
theme(
axis.text.x = element_text(angle=90,hjust=1),
panel.grid.major.x = element_blank(),
panel.border = element_blank(),
axis.ticks.x = element_blank()) 
+ xlab("X label") +  ylab("Y label")


which gives us:

enter image description here

I'd like to use some math symbols on the x-axis ticks (for instance, $R_{ij}$). I followed this solution but it is not working for me. Note that I tried expression('$R_{ij}$') and TeX('$Q_{ij}$') inside scale_x_discrete thru labels. How can I print as in LaTeX for the x ticks? I have used TeX in the past within xlab in ggplot, but apparently something is going on with scale_x_discrete.

like image 292
nhern121 Avatar asked Apr 27 '18 08:04

nhern121


1 Answers

All you have to do is to parse(text = ...) the TeX-expressions:

ggplot(dfvi, aes(x=x.names, y=rel.imp)) +
  geom_segment( aes(x=x.names, xend=x.names, y=0, yend=rel.imp),color="grey") +
  geom_point( color="orange", size=4) +
  scale_y_continuous(breaks=c(-1,seq(0,8,2)))+
  scale_x_discrete(labels=c('a'='a','x'='x',
                            'd'=TeX('$mode(L_{ij})$'),
                            'ft'=parse(text = TeX('$R_{ij}$')),
                            'ew'=parse(text = TeX('$Q_{ij}$')),
                            'qw'='qw','ccc'='ccc','sas'='sas','imb'='imb','msf'='msfff'))
....

Note: You might change the font size. I used axis.text.x = element_text(angle=90,hjust=1, size = 12).

enter image description here

like image 151
loki Avatar answered Sep 29 '22 08:09

loki