0

我有以下数据:

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。

提前致谢。

美联社

4

3 回答 3

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

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

在此处输入图像描述

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

于 2017-08-02T09:13:31.870 回答
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默认使用)。因此,您可以自己计算最小值和最大值,并添加一些 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))

在此处输入图像描述

于 2017-08-02T09:32:14.080 回答
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)
于 2017-08-02T09:22:32.857 回答