I would like to create a simple histogram with ggplot2, and my problem is that my variable x contains long lines so that the labels are overlaid.
Here is the fake data and plot:
library(dplyr) library(tidyr) library(ggplot2) set.seed(42) datas <- data.frame(label = sprintf("aLongLabel%d", 1:8), ok = sample(seq(0, 1, by = 0.1), 8, rep = TRUE)) %>% mutate(err = abs(ok - 1)) %>% gather(type, freq, ok, err) datas %>% ggplot(aes(x = label, y = freq)) + geom_bar(aes(fill = type), stat = "identity")

I would like to replace the labels with shorter ones and create a legend to show matches.
What I tried:
I use the aes form parameter in geo_point, which will create a legend with shapes (and shapes that I hide with alpha = 0 ). Then I change the shapes to scale_shape_manual and replace the x shortcuts with scale_x_discrete . With guides I redefine the alpha parameter of my shapes so that they are not invisible in the legend.
leg.txt <- levels(datas$label) x.labels <- structure(LETTERS[seq_along(leg.txt)], .Names = leg.txt) datas %>% ggplot(aes(x = label, y = freq)) + geom_bar(aes(fill = type), stat = "identity") + geom_point(aes(shape = label), alpha = 0) + scale_shape_manual(name = "Labels", values = x.labels) + guides(shape = guide_legend(override.aes = list(size = 5, alpha = 1))) + scale_x_discrete(name = "Label", labels = x.labels)

This gives me the expected result, but I feel that it is very hacks.
Is there any way ggplot2 do this more directly? Thanks.
r ggplot2 legend
Julien navarre
source share