在R中绘制堆积条形图

时间:2011-09-28 12:47:33

标签: r plot

我想在R中创建直方图[堆积条形图],其数据如下:

Period = c(1,1,2,2,3,3,4,4)                              
Sample = c("A","B","A","B","A","B","A","B")
Value1 = c(3,2,6,7,3,2,1,2)
Value2 = c(1,0,5,2,2,0,2,5)
x <- data.frame(Period,Sample,Value1,Value2)

是否可以在X轴上设置“Period”和“Sample”,在“Stacked Bar Plot”中设置值(“Value1”和“Value2”)。所以第一个直方图的高度为4(Value1和Value2分开) 提前谢谢你的帮助! 最好的问候。

2 个答案:

答案 0 :(得分:19)

您正在描述堆积条形图,而不是直方图。使用ggplot,您可以按以下方式执行此操作:

library(ggplot2)
library(reshape2)

x <- data.frame(
  Period = c(1,1,2,2,3,3,4,4),
  Sample = c("A","B","A","B","A","B","A","B"),
  Value1 = c(3,2,6,7,3,2,1,2),
  Value2 = c(1,0,5,2,2,0,2,5)
)

mx <- melt(x, id.vars=1:2)
ggplot(mx, aes(x=Period, y=value, fill=variable)) + 
  geom_bar(stat="identity") + 
  facet_grid(~Sample)

enter image description here

答案 1 :(得分:7)

它不如ggplot解决方案那么漂亮但是

v <- rbind(Value1,Value2)
barplot(v,beside=FALSE,names=levels(interaction(Period,Sample)),legend=TRUE)

似乎有效。