2017-06-23 66 views
1

我想创建一个具有三个不同图例的堆叠barplot,用于不同的数据分组。多个传说中的barplot填充ggplot

例如,给出以下数据框:

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) 

我想绘制逐年每个类别的计数堆叠barplot。

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

然而,而不必为类别(如上面)一个传奇,我想通过地区有三个传说与类别的子集(即标题为“REGION1”会显示“A”类和“b”的传说;标题为“region2”的图例将显示类别“c”和“d”;标题为“region3”的图例将显示类别“e”和“f”。 Legends for multiple fills in ggplotR: Custom Legend for Multiple Layer ggplot。 但是,我没有运气将它们应用到一个barplot。任何帮助将不胜感激!

回答

0

有时你可以通过将图层映射到额外的美学,然后使用override.aes来使这些美学的传说看起来像你希望的那样,以“硬”的方式做这种事情。这并不漂亮。

下面是一个例子,其中该图例fill抑制和图例经由colorsizealpha为三个“区域”的子集制备。

首先,获取ggplot2颜色为6种颜色如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

谢谢 - 很欣赏的帮助! – Powege

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得到灵感