Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - ggplot2 Newline character usable by parse(text=X)

I am trying to insert a deliberate line break into the axis title of ggplot2. As shown by the MWE below, I am using parse(text=X) to evaluate the possible LaTeX style inclusion of Greek characters and sub/super-scripts. I have seen that that the labeler tool of ggpot2 and expression objects should be able to process a new line character such as \n. But I am committed to using parse(text=X). I have had no success incorporating this in my x and y axis title strings however.

  • In the hard-coded MWE I loose everything after the \n.
  • When I import this as *{"\n"}* from an external table, I get the same behavior as *.

Which leads me to suspect that parse(text=X) doesn't support the new line symbol. If this is the case, what is the appropriate way to insert a new line?

In the past I have been able to use atop but prefer to try and use something different this time because it leaves too much blank space between lines. So alternatively, I would accept an answer that demonstrates how to customize the spacing of atop.

MWE:

library(ggplot2)
library("grid")

print("Program started")

gg <- ggplot(diamonds, aes(clarity, fill=cut))
gg <- gg + geom_bar(position="dodge")
gg <- gg + labs(y=parse(text="ahhhh\nWe~are~here"), x=parse(text="ahhhh\nWe~are~here"),title="title")

gg <- gg + theme(
                legend.justification=c(0,1),
                legend.position=c(0,1),
                legend.title=element_blank(),
                plot.background=element_rect(fill="red")
);
gg <- gg + guides(fill=guide_legend(title.position="top"))

print(gg)

print("Program complete - a graph should be visible.")
like image 805
EngBIRD Avatar asked Nov 01 '22 07:11

EngBIRD


1 Answers

Wrap your text in additional single quotes inside double-quotes and you'll get two-line labels on axes.

gg + labs(y=parse(text="'ahhhh\nWe~are~here'"), x=parse(text="'ahhhh\nWe~are~here'"),title="title")

You can construct plotmath output with combinations of single-quoted strings and expressions with some limitations - for example that your single-quoted string can not end with \n Check this code

parse(text = "'ahhhh\nWe' ~are%=>% bold(here[123])")      # it works
parse(text = "'ahhhh\n' We~are%=>% bold(here[123])")      # it throws an error
like image 185
inscaven Avatar answered Nov 09 '22 16:11

inscaven