2017-08-02 171 views
0

我有以下数据:添加额外的价值ggplot barplot

Sp Type Val1 Val2 
A One  200  50 
A Two  100  10 
C One  300  150 
C Two  200  10 

我做了如下得到堆叠barplot:

ggplot() + 
    geom_bar(data=test, aes(y = Val1, x = Sp, fill = Type), stat="identity",position='stack') 

因此,我得到两个堆叠的酒吧为A,B各堆叠的1型& 2(A的总尺寸是200 + 100 = 300)。这里,val2是每个类型中未知数的一小部分。我如何覆盖堆栈的各个部分?即在Val1中的A型中,未知的部分是Val2。

在此先感谢。

AP

+0

请更精确。你想在Val1上面叠加Val2吗?或者你想要一个包含两个值的堆叠barplot? – Jimbou

+0

它是Val2阴影的堆叠式barplot。我的意思是我想在Val1酒吧里添加Val2。即A将会有2个堆栈,1个有200个,2个有100个。在200个堆栈中,我想用50个和100个区域来遮蔽10个区域。如果我们有50和10个相同的颜色,它看起来就像两个堆栈中标记的比例! – Arun

+0

好的,然后看看我的答案!其他人只是总结Val1和Val2。 – Jimbou

回答

1

你可以试试:

d$xmin <- rep(c(0.55, 1.55),each=2) 
d$xmax <- rep(c(1.45, 2.45),each=2) 
d$ymin <- c(100, 0, 200, 0) 
d$ymax <- c(150, 10, 350, 10) 

ggplot(d) + 
    geom_col(aes(x=Sp, y=Val1, fill=Type)) + 
    geom_rect(aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), alpha=0.5) 

的想法是在酒吧手动添加矩形(我在这里使用geom_col因为此功能默认使用stat_identity)。因此,您可以自己计算分钟数和最大值,并添加一些阿尔法来重新绘制条形图。

或者你可以尝试更自动化的解决方案dplyr

library(tidyverse) 
d %>% 
    arrange(Sp, -as.numeric(Type)) %>% 
    mutate(ymin=ifelse(Type=="One",lag(Val1),0), 
     ymax=ifelse(Type=="Two",Val2, lag(Val1)+Val2)) %>% 
    mutate(Sp_n=as.numeric(Sp)) %>% 
    ggplot() + 
    geom_col(aes(x=Sp_n, y=Val1, fill=Type))+ 
    geom_rect(aes(xmin=Sp_n-0.45, xmax=Sp_n+0.45, ymin=ymin, ymax=ymax), 
    fill="white", alpha= 0.7) + 
    scale_x_continuous(breaks = 1:2, labels = unique(d$Sp)) 

enter image description here

2

这就是你正在寻找?:

library(ggplot2) 
data <- data.frame(Sp = c("A","A","C","C"), 
        Type = c("one","two","one","two"), 
        Val1 = c(200,100,300,200), 
        Val2 = c(50,10,150,10)) 
library(reshape2) 
data <- melt(data, id=c("Sp","Type")) 
data$Type2 <- paste(data$Type, data$variable, sep="_") 

[更新] 你熔化后得到的数据:

Sp Type variable value Type2 
1 A one  Val1 200 one_Val1 # it has value of 200 for Sp A 
2 A two  Val1 100 two_Val1 # it has value of 100 for Sp A 
3 C one  Val1 300 one_Val1 
4 C two  Val1 200 two_Val1 
5 A one  Val2 50 one_Val2 
6 A two  Val2 10 two_Val2 
7 C one  Val2 150 one_Val2 
8 C two  Val2 10 two_Val2 

one_Val1等于和two_Val1至 - > 200 + 100 = 300

ggplot() + 
    geom_bar(data=data, aes(y = value, x = Sp, fill = Type2), stat="identity",position='stack') 

enter image description here

我在第一数据已被熔化以得到在一列VAL1和val2的值,以进一步使用它,并将它与类型列粘贴在一起。

+0

对于您的解决方案,A的总大小不会达到300(200 + 100)。 – Jimbou

+0

one_Val1 and two_Val1 = 300 - >这是类型1的Sp:A –

+0

没有一个是不正确的。 – Jimbou

1

如果你想让它每VAL1/VAL2分值

library(ggplot2) 
library(reshape2) 
test <- melt(test, id=c("Sp","Type")) 
ggplot(data=test) + 
    geom_bar(aes(y = value, x = Sp, fill = Type), stat="identity",position='stack')+ 
    facet_wrap(~variable)