Patel
Patel

Reputation: 13

Error in creating grouped bar chart with ggplot

Dear Stackoverflow users,

I would like to create group bar chart using ggplot. Here is the sample data

> data
                            X0h     X3h     X6h     X9h    X12h
aldehyde_dehydrgenase   -0.7970 -0.7423 -0.5425 -0.6721 -0.6804
lactate_dehydrogenase    0.6737  0.5131  0.5063  0.4767  0.3628
aldehyde_reductase Akr1  0.4701  0.5694  0.2096  0.2696  0.2492

data <- read.csv("fig2.csv", header=T, row.names=1)
mat.melted <- melt(as.matrix(data), value.name = "expression", varnames=c('Enz', 'TimePoint'))

ggplot(mat.melted, aes(x=Enz, y=TimePoint, fill=expression)) +  geom_bar(position=position_dodge(), stat="identity", colour='black')

This I got from the above enter image description here

The bars should be like as below (created using barplot function on same data)
enter image description here

Upvotes: 1

Views: 144

Answers (1)

cody_stinson
cody_stinson

Reputation: 400

The gather() command within the tidyverse package can make this a bit easier. Tidyverse loads ggplot2 as well. See the code below. It appears to replicate your desired output.

library(tidyverse)

data <- read.csv("fig2.csv", header=T, row.names=1

### Melt the data using gather ###
graph <- data %>% 
  gather(hour, expression, -NameOfFirstColumn) %>% 
  arrange(name)

### Plot the data using ggplot2 ###
ggplot(graph, aes(x = name, y = expression, fill = hour)) +
  geom_bar(stat = "identity", position = "dodge")

enter image description here

Upvotes: 1

Related Questions