I would like to automatically wrap my labels in ggplot2, i.e. insert line breaks of long labels. Here is written how to write a function (1) for it, but sadly I do not know where to put labeller=label_wrap
in my code (2).
(1) function by hadley
label_wrap <- function(variable, value) { lapply(strwrap(as.character(value), width=25, simplify=FALSE), paste, collapse="\n") }
(2) code example
df = data.frame(x = c("label", "long label", "very, very long label"), y = c(10, 15, 20)) ggplot(df, aes(x, y)) + geom_bar(stat="identity")
I'd like to wrap some of the longer labels here.
To increase the X-axis labels font size using ggplot2, we can use axis. text. x argument of theme function where we can define the text size for axis element.
Use 'wrap_labs()' to wrap the title, subtitle, and caption of a ggplot2 chart onto multiple lines, left-align them, and split 'notes' and 'source' onto multiple lines.
You don't need the label_wrap
function. Instead use the str_wrap
function from the stringr
package.
You do not provide your df
data frame, so I create a simple data frame, one that contains your labels. Then, apply the str_wrap
function to the labels.
library(ggplot2) library(stringr) df = data.frame(x = c("label", "long label", "very, very long label"), y = c(10, 15, 20)) df df$newx = str_wrap(df$x, width = 10) df
Now to apply the labels to a ggplot chart: The first chart uses the original labels; the second chart uses the modified labels; and for the third chart, the labels are modified in the call to ggplot.
ggplot(df, aes(x, y)) + xlab("") + ylab("Number of Participants") + geom_bar(stat = "identity") ggplot(df, aes(newx, y)) + xlab("") + ylab("Number of Participants") + geom_bar(stat = "identity") ggplot(df, aes(x, y)) + xlab("") + ylab("Number of Participants") + geom_bar(stat = "identity") + scale_x_discrete(labels = function(x) str_wrap(x, width = 10))
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