大小范围内的堆叠条形图的R函数

我想为尺寸范围创建条形图。我展示了一个虚拟数据集(数据)

Size1   Size2    A     B      C
0        5     0.3    0.5   0.2
5       10     0.1    0.2   0.7
10      20     0.5    0.2   0.3
20      50     0.2    0.4   0.4
50      100    0.7    0.1   0.2

如果只有一个“大小”,我可以创建一个图。例如,如果只有“ Size2”,我会做类似的事情

library(reshape2)
data1 <- melt(data,id.var="Size2")

library(ggplot2)
ggplot(data1,aes(x = Size2,y = value,fill = variable)) + 
  geom_bar(stat = "identity")

有了这个我得到 https://imgur.com/z0zUiwm

但是,我想要在每个尺寸范围内绘制A,B,C的图。因此,在x轴上显示“大小”,在y轴上显示A,B和C的百分比,我该如何进一步进行操作。我希望将小节的线连接起来,即x轴上的小节之间没有间隙。

hunanldxyl 回答:大小范围内的堆叠条形图的R函数

一种方法是:

size1 <- c(0,5,10,20,50)
size2 <- c(5,50,100)
A = c(0.3,0.1,0.5,0.2,0.7)
B <- c(0.5,0.4,0.1)
C <- c(0.2,0.7,0.3,0.2)

data <- data.frame(Size1=factor(size1),# this removes gaps between bars in x axis)
                 Size2=factor(size2),A=A,B=B,C=C)
library(reshape2)
library(dplyr)
data1 <- melt(data[,c("Size1","A","B","C")],id.var="Size1")
data2 <- melt(data[,c("Size2",id.var="Size2")

library(ggplot2)
g1 <- ggplot(data1,aes(x = Size1,y = value,fill = variable,)) + 
  geom_bar(stat = "identity",show.legend = FALSE)
g2 <- ggplot(data2,aes(x = Size2,fill = variable)) + 
  geom_bar(stat = "identity")

g1 <- ggplotGrob(g1)
g2 <- ggplotGrob(g2)
g <- cbind(g1,g2)
library(grid)
grid.newpage()
grid.draw(g)

两个条形图看起来相同,因为size1,size2的A,B和C值相同。

本文链接:https://www.f2er.com/3157838.html

大家都在问