Created
March 26, 2021 16:00
-
-
Save sharlagelfand/75a123672aefc5bbe8bdbaeec7633ab4 to your computer and use it in GitHub Desktop.
Demonstrating the usage of the argument `labeller = label_wrap_gen()` in the ggplot2 function facet_wrap()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
library(tibble) | |
df <- tribble( | |
~x, ~y, ~label, | |
1, 2, "A super long label oh god how am I going to deal with this", | |
2, 1, "A shorter one" | |
) | |
# Default - text is cut off | |
ggplot(df) + | |
geom_point(aes(x = x, y = y)) + | |
facet_wrap(vars(label)) | |
# With label_wrap_gen(), the label wraps (the default width is 25 characters but you can change it!) | |
ggplot(df) + | |
geom_point(aes(x = x, y = y)) + | |
facet_wrap(vars(label), labeller = label_wrap_gen()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about something like this:
Function to insert line breaks in a vector of strings
This function assumes the maximum string length is less than 2*MaxLen
LineBrk <- function(x,MaxLen) {
NewStr <- vector()
for (i in 1:length(x)) {
len <- str_length(x[i])
j <- 0
if (len>MaxLen) {
while (substr(x[i],len%/%2+j,len%/%2+j)!=" ") j <- j+1
NewStr[i] <- paste0(substr(x[i],1,(len%/%2+j-1)),"\n",
substr(x[i],(len%/%2+j+1),len))
} else {
NewStr[i] <- x[i]
}
}
y <- NewStr
}