'How to add legends to the barplot in R like shown in the below image?

I want to implemeenter image description herent legend like tjhis



Solution 1:[1]

As far as I get it you want a legend with the label for the first key on the left and the label for the last one on the right. TBMK there is no out-of-the-box option to have the legend text on different sides of the keys.

But one option or hack to achieve this kind of legend would be "remove" the legend key labels for all keys except for the last and use the label for the first key as the legend title. To get the same style you probably have to set the same style for the legend.title as for the legend.text using theme options.

Using mtcars as example data:

library(ggplot2)

ggplot(mtcars, aes(am, fill = factor(cyl))) +
  geom_bar(position = "fill") +
  scale_fill_discrete(labels = function(x) { x[seq(1, length(x) - 1)] <- ""; x } ) +
  theme(legend.position = "top", legend.title = element_text(size = rel(.8))) +
  labs(fill = 4)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 stefan