Reputation: 65
structure(list(Young = c(FALSE, TRUE), pop = c(221294L, 574721L), p = c(0.278002298951653, 0.721997701048347)), class = "data.frame", row.names = c(NA, -2L))
I'm looking to make a stacked bar graph using my data frame, however when I use ggplot I continue to get the error.
Error: stat_count() can only have an x or y aesthetic.
ggplot(data = young, aes(x = Young, y = p)) + geom_bar(position = "fill") + labs(x = "Age Bracket", y = "Proportion")
Could anyone explain to me why R won't produce the bar chart, and what corrections I can make to the above code to produce a stacked bar chart using proportions in "p" column?
Thanks
Upvotes: 1
Views: 56
Reputation: 21287
You need stat="identity"
in geom_bar
.
ggplot(data = young, aes(x = Young, y = p)) + geom_bar(position = "fill", stat = "identity") + labs(x = "Age Bracket", y = "Proportion")
To get a single stacked bar, define a new variable as shown below.
young$state <- c("TrueorFalse","TrueorFalse")
p <- ggplot(data = young, aes(x = state, y = p, fill=Young)) + #
geom_bar(position="stack", stat="identity") +
labs(x = "Age Bracket", y = "Proportion")
p
Upvotes: 0
Reputation: 101099
I guess this might be what you are after
ggplot(data = cbind(id = 1,young), aes(x = id, y = p, fill = Young)) +
geom_bar(position = "fill", stat = "identity") +
labs(x = "Age Bracket", y = "Proportion")
Upvotes: 1