I have a series of water quality graphs each made separately using a for loop and then added to together using cowplot's plot_grid().
The labels on the y axis take up a lot of space and I'm trying to make it look less complicated. I'd like to have the main axis title, e.g., temperature, in a larger font size than the units, e.g., (oC). Currently all the labels are in a list that the for loop references. e.g. axis labels <- list('Temp' = c('Temperature','(\u00B0C)'))
I have the units and temperature as separate items within the list. Is there a way to do this as part of the y label? This is what I currently use, but only adds one part with the full label:
labs(x= 'Sampling Site', y= axisLabels[[category]][1])
And produces something like this (without the celcius):
UPDATE
When I set the font-family to Calibri it makes the spaces quite large. Is there a way to change this?
axisLabels <- lapply(axisLabels, function(x) {
x[[1]] <- paste0("<span style='font-size: 13pt; font-family: Calibri'>", x[[1]])
x[[2]] <- paste0("<span style='font-size: 10pt;font-family: Calibri'>", x[[2]], "</span>")
return(x)
})
With above code v previously without it
CodePudding user response:
One option would be the ggtext
package which via the theme element ggtext::element_markdown
allows to use a bit of HTML and CSS to style the axis text. In the example below I wrap the units of your text labels inside a <span>
tag for which I set the font size to 8pt. Note: As we are now in the world of HTML we have to use a <br>
tag to add a line break:
library(ggplot2)
library(ggtext)
axisLabels <- list("Temp" = c("Temperature", "(\u00B0C)"))
# Set font size for units to 6pt
axisLabels <- lapply(axisLabels, function(x) {
x[[2]] <- paste0("<span style='font-size: 8pt'>", x[[2]], "</span>")
return(x)
})
category <- "Temp"
ggplot(mtcars, aes(hp, mpg))
geom_point()
theme_bw()
labs(x = "Sampling Site", y = paste(axisLabels[[category]], collapse = "<br>"))
theme(axis.title.y = ggtext::element_markdown())