首页 文章

barplot的多个图例填写ggplot [复制]

提问于
浏览
1

这个问题在这里已有答案:

我想为不同的数据分组创建一个带有三个不同图例的堆叠条形图 .

例如,给定以下数据帧:

Year <- as.factor(c(rep(1, 10), rep(2, 10), rep(3,10), rep(4,10), rep(5,10), rep(6,10)))
Category <- as.factor(c(rep("a", 15), rep("b", 10), rep("c", 10), rep("d",10), rep("e", 10), rep("f", 5)))
Region <- as.factor(c(rep("region1", 25), rep("region2", 20), rep("region3",15)))
data <- data.frame(Year, Category, Region)

我想绘制每年按类别计算的堆积条形图 .

ggplot() + geom_bar(data=data,aes(x=Year, fill=Category))

但是,我不希望有一个类别的传奇(如上所述),我希望有三个传说,按类别按类别子集(即 Headers 为“region1”的图例将显示类别“a”和“b”; Headers 为“region2”的图例将显示类别“c”和“d”; Headers 为“region3”的图例将显示类别“e”和“f” .

我试过引用这两个线程:Legends for multiple fills in ggplotR: Custom Legend for Multiple Layer ggplot . 但是,我没有运气将它们应用到一个条形图 . 任何帮助将不胜感激!

2 回答

  • 0

    你有时可以通过将图层映射到其他美学来做这种事情,然后使用 override.aes 使基于这些美学的图例看起来像你想要的那样 . 它不漂亮 .

    下面是一个示例,其中 fill 图例被抑制,并且通过 colorsizealpha 为三个"region"子集创建了图例 .

    首先,获取6种颜色的ggplot2颜色,如here所示 .

    gg_color_hue = function(n) {
        hues = seq(15, 375, length = n + 1)
        hcl(h = hues, l = 65, c = 100)[1:n]
    }
    
    cols = gg_color_hue(6)
    

    包含三个无关的 geom_point 层只是为了将三个图例添加到图中;通过将 size 设置为0或 color 为NA来抑制实际点 .

    然后是 guide_legend 中的杂乱工作,其中每个图例都会根据上面的 cols 更改为显示正确的颜色 . 更改图例名称并设置图例顺序 .

    ggplot(data = data, aes(x = Year) ) +
        geom_bar( aes(fill = Category), show.legend = FALSE ) +
        geom_point(data = subset(data, Category %in% c("a", "b") ),
                   aes(color = Category), stat = "count", size = 0) +
        geom_point(data = subset(data, Category %in% c("c", "d") ),
                   aes(size = Category), stat = "count", color = NA) +
        geom_point(data = subset(data, Category %in% c("e", "f") ),
                   aes(alpha = Category), stat = "count", size = 0) +
        guides(color = guide_legend(title = "Region 1", order = 1, 
                                    override.aes = list(shape = 15, size = 5, color = cols[1:2]) ),
               size = guide_legend(title = "Region 2", order = 2, 
                                    override.aes = list(shape = 15, size = 5, color = cols[3:4]) ),
               alpha = guide_legend(title = "Region 3", order = 3, 
                                    override.aes = list(shape = 15, size = 5, color = cols[5:6], alpha = 1) ) ) +
        theme(legend.key = element_rect(fill = "white") )
    

    enter image description here

  • 0

    这样的事情怎么样:

    ggplot() + geom_bar(data=data,aes(x=Year, fill=Category, color=Region)) + scale_fill_brewer(palette="Greens") + scale_color_manual(values = c("red", "black", "grey"))

    使用scale_color_manual进行自定义 . 你可以从http://colorbrewer2.org/#type=sequential&scheme=BuGn&n=3获得灵感

相关问题