繁体   English   中英

如何将数据传递到R中的堆积条形图?

[英]How do I pass data to a stacked bar chart in R?

我有一个csv文件,其中的数据结构如下:

model,pass,fail
a,10,5
b,5,10
c,15,5

我想制作一个堆积的条形图,如下所示: 堆积条形图

我尝试使用以下代码(数据是导入的csv文件的名称):

barplot(as.matrix(data), col=c("light green","light yellow"))
legend("topright", fill=c("light green","light yellow"), legend=rownames(data))

...但是这会将标头名称作为数据点。 如何将“数据”传递给barplot函数,以便每个模型(a,b,c)都是一个条形图?

(由于我是R的新手,所以我现在不希望使用任何类似ggplot的库)

> model <- c("a", "b", "c")
> pass <- c(10, 5, 15)
> fail <- c(5, 10, 5)
> dat <- data.frame(model, pass, fail)
> 
> library(ggplot2)
> library(reshape2)
> dat <- melt(dat)
Using model as id variables
> dat
  model variable value
1     a     pass    10
2     b     pass     5
3     c     pass    15
4     a     fail     5
5     b     fail    10
6     c     fail     5
> ggplot(dat, aes(x = model, y = value, fill = variable)) + geom_bar(stat = "identity")

在此处输入图片说明

如果您不想使用ggplot2软件包,可以尝试

model <- c("a", "b", "c")
pass <- c(10, 5, 15)
fail <- c(5, 10, 5)
dat <- data.frame(pass, fail)
dat <- t(dat)
rownames(dat) <- model

barplot(dat, xlab = "Model", col = c("light green","light yellow")) 
legend("top", legend = rownames(dat), fill = c("light green", "light yellow"))

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM