创建具有多个图例的堆叠条形图(每个条形图一个)

时间:2020-06-09 16:06:11

标签: r ggplot2 legend stacked-chart


我想用ggplot2创建的堆积条形图从一个图例中制作多个图例(7)。目标是为七个小节中的每个小节都有一个图例,但不幸的是,我不知道该怎么做。在此先感谢您的帮助!


这就是我已经拥有的代码:

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")

0 个答案:

没有答案