我有一个数据框,我想通过使用ggplot来制作直方图。我希望在x轴和y轴上有森林,农业,建筑,其他和水,对于每个土地使用都会有委任和遗漏错误。有人可以帮我吗。谢谢
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")))
答案 0 :(得分:3)
或者这种替代方案适合吗?
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~.)
答案 1 :(得分: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")