在R中绘制堆积条形图

Eco*_*o06 6 plot r

我想在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)
Run Code Online (Sandbox Code Playgroud)

是否可以在X轴上设置"Period"和"Sample",在"Stacked Bar Plot"中设置值("Value1"和"Value2").所以第一个直方图的高度为4(Value1和Value2分开)感谢您的帮助!最好的祝福.

And*_*rie 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Ben*_*ker 7

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

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

似乎工作.