r - Create abbreviated legends manually for long X labels in ggplot2 -


i create simple bar chart ggplot2 , problem x variable contains long strings labels overlaid.

here fake datas , plot :

library(dplyr) library(tidyr) library(ggplot2)  set.seed(42) datas <- data.frame(label = sprintf("alonglabel%d", 1:8),             ok = sample(seq(0, 1, = 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") 

enter image description here

i replace labels shorter ones , create legend show matches.

what i've tried :

i use shape aes parameter in geo_point create legend shapes (and plots shapes hide alpha = 0). change shapes scale_shape_manual , replace x labels scale_x_discrete. guides override alpha parameter of shapes wont invisible in 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) 

enter image description here

it gives me expected output feel hacky.

does ggplot2 provides way more directly ? thanks.

rotation solution suggested pascal

rotate labels , align them edge :

datas %>%    ggplot(aes(x = label, y = freq)) +    geom_bar(aes(fill = type), stat = "identity") +    theme(axis.text.x = element_text(angle = 90, hjust = 1)) 

enter image description here


Comments