为 ggplot barplot 添加额外的值

Add extra value to ggplot barplot

我有以下数据:

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

我做了以下操作来获得堆叠条形图:

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

这是您要找的吗?:

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 等于 200two_Val1 等于 100 --> 200 + 100 = 300

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

我首先融化了您的数据以在一列中获取 Val1 和 Val2 的值以进一步使用它并将其与类型列粘贴在一起。

以防您希望它按 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)

你可以试试:

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)。因此,您自己计算最小值和最大值,并添加一些 alpha 来绘制条形图。

或者您可以尝试更自动化的 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))