Reputation: 397
I have a dataframe and I want to make a histogram out of it by using ggplot. I want to have Forest, Agriculture, Built-up, Other and Water in the x-axis and in the y axis would be both comission and omission errors for each land use. Can someone help me out. Thanks
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")))
Upvotes: 2
Views: 8807
Reputation: 3501
Or would this alternative fit?
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~.)
Upvotes: 4
Reputation: 145755
With ggplot, when you want things to share a dimension (e.g., x-axis, color), you want them in one column. So we start by reshaping your data into long form with reshape2::melt
library(reshape2)
library(scales) # for percent formatter
longdf <- melt(n)
names(longdf) <- c("Error", "Land_Use", "Measure")
Then the plotting is easy.
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")
Upvotes: 1