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.
\n
.*{"\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.")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With