[英]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.