2017-11-03 125 views
1

尊敬的用户配置了Stackoverflow,使用ggplot创建分组条形图时出错

我想使用ggplot创建组条形图。下面是示例数据

> 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') 

这我从上述 enter image description here

得到的条应该像如下
enter image description here

回答

1

的收集(使用barplot上相同的数据的功能创建)( )在tidyverse软件包中的命令可以使这一点更容易一些。 Tidyverse也加载ggplot2。请参阅下面的代码。它似乎复制你想要的输出。

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

+0

它给错误:>图表<- data %>% +聚集(小时,表达,-name)%>% +安排(名称) 错误的typeof(X):对象“名'找不到 – Patel

+0

这是因为我在你的示例数据中命名了第一个变量“name”。您上面提供的样本数据没有第一列的变量名称,所以我将其称为“名称”。将其替换为您称为包含醛脱氢酶等的变量 –