K. Maya
K. Maya

Reputation: 299

R function for a stacked barplot in a size range

I want to create a barplot for a size range. I present a dummy dataset (data)

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

I can create a plot if there was just one "Size". For example if there was only "Size2" I'd do something like

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

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

With this I get https://i.sstatic.net/iTNtE.jpg

However, I want a plot for A, B, C within each size range. So with Size on the x-axis and percent of A, B, and C on the y-axis, how can I proceed further. I want the lines of the barplot to be connected i.e no gaps between bars in the x-axis.

Upvotes: 1

Views: 88

Answers (1)

Tianyu Z
Tianyu Z

Reputation: 151

One way is to it is:

size1 <- c(0,5,10,20,50)
size2 <- c(5,10,20,50,100)
A = c(0.3,0.1,0.5,0.2,0.7)
B <- c(0.5,0.2,0.2,0.4,0.1)
C <- c(0.2, 0.7,0.3,0.4,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","A","B","C")], 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, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

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

Two barplots look the same because the value of A, B and C are the same for size1 and size2.

Upvotes: 1

Related Questions