In the following example (please notice differences in y-axis labels) I use a variable to fill in an axis label in ggplot2
. Interestingly ~
produces much larger spaces, and extra spaces show up around an enlarged -
.
library(ggplot2)
#LabelY <- "Miles per Gallon-Car"
LabelY <- parse(text="Miles~per~Gallon-Car")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab(LabelY) + ylab(LabelY) +
theme(text=element_text(size=16))
print(a)
I am using parse because it allows me to use more complex examples including atop
and greek letters.
Is there a way I can make use of parse to import complex strings while also preserving the desired "less spread out" appearance of the content?
It looks like enclosing the hyphenated term with backticks will allow you to keep the hyphen instead of turning it in a dash.
Here I put the new hyphenated version of the axis label on the x axis and leave the y axis as the original for comparison.
LabelY <- parse(text="Miles~per~Gallon-Car")
LabelY2 <- parse(text="Miles~per~`Gallon-Car`")
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab(parse(text = LabelY2)) + ylab(LabelY) +
theme(text=element_text(size=16))
As you pointed out in the comments, you can also use a curly bracket and single quote combination around the hyphenated term to get the same effect.
parse(text="Miles~per~{'Gallon-Car'}")