1
votes

I have a data set which I want to plot in a bar plot. It consists of a x-variable, two y-variables showing percentages, and a variable giving the variables different features (like A, B and C). The sum of all y-variables at the same x is 100%.

I have constructed an example for the data frame:

x <- c(0,0,0,50,50,50,100,100,100)
y1 <- c(40,30,5,60,10,5,65,5,5)
y2 <- c(10,10,5,10,10,5,10,10,5)
AB <- c('B','A','C','B','A','C','B','A','C')
test <- data.frame(x,y1,y2,AB)

I want to construct a plot which shows the percentages at different x-values, contrasting the values in y1 and y2. I was able to put it all in a plot, showing y1 in transparent:

p <- ggplot(test,aes(x=x, group=x)) +
  geom_col(aes(y=y1,fill=AB)) +
  geom_col(aes(y=y2,fill=AB)) +
  scale_fill_manual(values = alpha(c("darkred","darkgreen","blue"),0.6)) +
  coord_flip()
p

You can see the plot here

Now I want to re-arrange the values in the plot such as both the normal and the transparent values of either A, B or C are next to each other. I want to compare both the proportion of transparent and non-transparent values (y1 and y2) and of the different features (A, B, C), which is only possible when all values of e.g. A are next to each other.

Is it possible to mix values from two gem_col with each other? I have no idea how to do it and could not find any solution yet.

1

1 Answers

0
votes

I think this is what you are looking for. Another answer can be found here: How to plot a Stacked and grouped bar chart in ggplot?

x <- c(0,0,0,50,50,50,100,100,100)
y1 <- c(40,30,5,60,10,5,65,5,5)
y2 <- c(10,10,5,10,10,5,10,10,5)
AB <- c('B','A','C','B','A','C','B','A','C')
test <- data.frame(x,y1,y2,AB)


barwidth = 20

ggplot(test) +
  geom_bar(mapping =  aes(x = x - barwidth/2, y= y1, fill = AB),
           stat = "identity",
           position = "stack",
           width = barwidth)+
  geom_bar(mapping =  aes(x = x + barwidth/2 + 1, y= y2, fill = AB),
           stat = "identity",
           position = "stack",
           width = barwidth)+
  scale_x_continuous(breaks = c(0,50,100))+
  scale_fill_manual(values = alpha(c("darkred","darkgreen","blue"),0.6)) +
  coord_flip()+
  labs(x = "x")+
  theme_minimal()

enter image description here