[英]plotting grouped bar charts in R
我正在嘗試在 R 中繪制此數據 -
column1 column2 column3
1-2 abc 10
1-2 def 15
1-2 ghi 20
2-3 abc 80
2-3 def 95
2-3 ghi 10
3-4 abc 30
3-4 def 55
3-4 ghi 80
x 軸將是 column1(因此 1-2、2-3 和 3-4 將作為 x 軸出現),並且在 y 軸上,應為每個 column2 元素繪制 column3 中的值。 所以這基本上是一個“分組”條形圖。
我無法使用 R 繪制此分組條形圖。我使用的代碼片段如下:
dataset <- fetch(rs,n=-1)
plot_var <- table(dataset$percentage, dataset$age)
barplot(plot_var, names.arg,
main="Title of Graph",
xlab="Column1", col=c("darkblue","red"),
legend = rownames(plot_var), beside=TRUE)
如何顯示此分組條形圖? 謝謝!
您的問題似乎歸結為錯誤的數據格式。 您需要使用正確的行名稱結構制作一個矩陣,以使用基本圖形創建您想要的繪圖。 這是您的解決方案:
#your data...
d <- data.frame(row.names=c("1-2","2-3","3-4"), abc = c(10,80, 30),
def = c(15, 95, 55), ghi = c(20, 10, 80))
#but you make a matrix out of it to create bar chart
d <- do.call(rbind, d)
#...and you are sorted
barplot(d, beside = TRUE, ylim=c(0,100), legend.text = rownames(d),
args.legend = list(x = "topleft", bty="n"))
但是,我有時喜歡將lattice
用於此類任務。 這次您甚至不必制作矩陣,只需將data.frame
保持為原始格式:
d <- data.frame(column1=rep(c("1-2","2-3","3-4"), each=3),
column2=rep(c("abc", "def", "ghi"), 3),
column3=c(10, 15, 20, 80, 95, 10, 30, 55, 80))
require(lattice)
barchart(column3 ~ column1, groups=column2, d, auto.key = list(columns = 3))
我喜歡將ggplot2
用於此類任務。
#Make the data reproducible:
column1 <- c(rep("1-2", 3), rep("2-3", 3), rep("3-4", 3))
column2 <- gl(3, 1, 9, labels=c("abc", "def", "ghi"))
column3 <- c(10, 15, 20, 80, 95, 10, 30, 55, 80)
d <- data.frame(column1=column1, column2=column2, column3=column3)
require(ggplot2)
ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(position=position_dodge())
我覺得這個直觀的原因(經過一段時間的學習)是你清楚地說明了你在 x 和 y 軸上想要什么,我們只是告訴 ggplot(以及哪個變量定義了“填充”顏色,以及哪種情節 - 在這里, geom_bar
- 使用。
我從 Drew Steen 的回答中找到了幫助,但上面的這段代碼對我不起作用,如上所示。 我添加了 stat="identity" 並且它有效。
require(ggplot2)
ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(stat="identity", position=position_dodge())
謝謝德魯的回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.