0


I would like to make multiple legends (7) out of one legend form my stacked bar chart, which I created with ggplot2. The goal is to have a legend for the sub clusters of each of the seven bar, but unfortunately I don't know how to do this. Thanks in Advance for you help!


Thats the code I already have:

library(ggplot2)

results.J <- data.frame(
    'Cluster'=c('1', '1', '2', '2', '2',
                '2', '3', '3', '4', '4',
                '4', '4', '5', '5', '5',
                '6', '6', '6', '6', '7',
                '7', '7', '7'),

    'Subcluster'=c("1.1", "1.2", "2.1", "2.2",
                   "2.3", "2.4", "3.1", "3.2",
                   "4.1", "4.2", "4.3", "4.4",
                   "5.1", "5.2", "5.3", "6.1",
                   "6.2", "6.3", "6.4", "7.1",
                   "7.2", "7.3", "7.4"),

    'Hits' = c(30, 2, 3, 300, 89, 20, 23, 50, 5,
               100, 20, 15, 201, 13, 23, 0, 69,
               5, 15, 1, 249, 0, 3))

results.J$Subcluster <- factor(results.J$Subcluster,
                               levels = unique(results.J$Subcluster))
g <- ggplot(data=results.J, aes(x=factor(Cluster),
                                y=Hits, fill=Subcluster)) 
g + geom_bar(stat = "identity", colour="black") +
    ggtitle("Search terms found") + xlab("Cluster") +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(legend.position = "bottom")
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
MLZ
  • 1
  • Hi MLZ. A legend in ggplot has to be linked to a _scale_. In your case, the legend displays the fill scale. You can only have a single fill scale per ggplot, so there will only be a single legend. It wouldn't be impossible to get the effect you are looking for, but it would essentially require you to create seven different plots and stitch them together. – Allan Cameron Jun 09 '20 at 17:12
  • See https://stackoverflow.com/questions/27803710/ggplot2-divide-legend-into-two-columns-each-with-its-own-title maybe it will help you – Rémi Coulaud Jun 09 '20 at 17:15
  • 1
    @AllanCameron is right. One scale, one legend. However, with the `ggnewscale` package you can add additional fill, color, ... scales and legends. See e.g. this post https://stackoverflow.com/questions/62208141/stacked-bar-plot-with-multiple-or-different-legend-for-each-group/62210288#62210288 on how to achieve that. – stefan Jun 09 '20 at 18:29
  • Thanks, that helped a lot and worked pretty well! – MLZ Jun 10 '20 at 13:08

0 Answers0