2014-11-06 132 views
1

我有一個數據框,我想用ggplot製作一個直方圖。我希望在x軸和y軸上有森林,農業,建築,其他和水,這對於每個土地利用來說都是遺漏和遺漏的錯誤。有人可以幫我嗎。謝謝使用ggplot在同一個直方圖中繪製兩個變量

dput(n) 
    structure(c(90.49964814, 36.77437804, 18.61958266, 57.14285714, 
    20, 100, 9.53346856, 45.63106796, 0, 0), .Dim = c(2L, 5L), .Dimnames = list(
     c("Omission Error", "Comission Error"), c("Forest", "Agriculture", 
     "Built-up", "Other", "Water"))) 

回答

2

或者這種方法是否合適?

library(reshape2); library(ggplot2) 
df2 <- melt(df, id.var=Forest) 
#     X1   X2  value 
# 1 Omission Error  Forest 90.499648 
# 2 Comission Error  Forest 36.774378 
# 3 Omission Error Agriculture 18.619583 
# 4 Comission Error Agriculture 57.142857 
# 5 Omission Error Built-up 20.000000 
# 6 Comission Error Built-up 100.000000 
# 7 Omission Error  Other 9.533469 
# 8 Comission Error  Other 45.631068 
# 9 Omission Error  Water 0.000000 
# 10 Comission Error  Water 0.000000 

ggplot(df2, aes(x=X2, y=value)) + geom_bar(stat="identity") + facet_grid(X1~.) 

enter image description here

+0

我正要用這個建議編輯我的答案。 – Gregor 2014-11-06 17:40:55

1

有了ggplot,當你想要東西共享一個維度(例如,x軸,顏色),你希望他們在一列中。因此,我們開始通過重塑你的數據爲長形式reshape2::melt

library(reshape2) 
library(scales) # for percent formatter 
longdf <- melt(n) 
names(longdf) <- c("Error", "Land_Use", "Measure") 

然後繪圖容易。

ggplot(longdf, aes(x = Land_Use, y = Measure/100, fill = Error)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    scale_y_continuous(labels = percent_format()) + 
    labs(x = "Land Use", y = "Error Percent", fill = "Error Type") 
+0

不知何故percent_format具有錯誤消息。 '找不到函數'percent_format' – 2014-11-06 17:45:32

+0

@SimonBesnard確保'install.packages(「scale」)'然後'library(scales)'第一個 – JasonAizkalns 2014-11-06 17:48:25

+0

非常感謝。 – 2014-11-06 17:55:13

相關問題