Chester
Chester

Reputation: 11

Creating a Grouped Bar Plot with Ggplot

How do I code for a grouped bar chart where I can depict 2 values for each strain: one column will represent cell volume for iron diet and another column will represent cell volume for normal diet?

My Excel table looks something like this where it has multiple columns but I want to selectively make a graph based on 3 of the columns (Strain, CV Iron, CV Normal):

Strain      CV Iron        CV Normal
A             23              17
B             10              15
...

I want my grouped bar chart to look something like this:

from https://www.r-graph-gallery.com/wp-content/uploads/2015/10/48_basic_barplot_ggplot2.png

The x-axis is the "Strain", and the y-axis would be "CV" where each Strain has 2 columns: one for "CV Iron" and one for "CV Normal", and the color coding of the columns would be based on Diet (CV Iron or CV Normal).

Upvotes: 1

Views: 2405

Answers (1)

Ibon Tamayo
Ibon Tamayo

Reputation: 91

I will use an example:

df1 <- data.frame(Strain = c("A","B","C","D"),
              CVIron = c(12,15,16,21),
              CVNormal = c(10,12,18,9))

head(df1) 
  Strain CVIron CVNormal
    1      A     12       10
    2      B     15       12
    3      C     16       18
    4      D     21        9

First of all, you should merge the two CV columns in one. You can use melt function in the reshape2 package.

library(reshape2)
df2 <- melt(df1, id = "Strain")

head(df2)
 Strain variable value
1      A   CVIron    12
2      B   CVIron    15
3      C   CVIron    16
4      D   CVIron    21
5      A CVNormal    10
6      B CVNormal    12
7      C CVNormal    18
8      D CVNormal     9

And then you can easily apply the ggplot function.

library(ggplot2)
ggplot(data=df2, aes(x=variable, y=value, fill=Strain)) +
   geom_bar(stat="identity", position=position_dodge())

enter image description here

Upvotes: 3

Related Questions