Skip to content

Instantly share code, notes, and snippets.

@multidis
Created December 13, 2013 20:59
Show Gist options
  • Save multidis/7951243 to your computer and use it in GitHub Desktop.
Save multidis/7951243 to your computer and use it in GitHub Desktop.
Bar graphs of counts. Stacked bar charts to compare their factor-fill in ggplot2.
## simplest case of counts-based bar graph
gpb <- ggplot(dfstr, aes(x=factor(age)))
gpb + geom_bar(stat="bin")
## add bar fill by another factor: add fill aes
gpb <- ggplot(dfstr, aes(x=factor(age), fill=factor(gender)))
gpb + geom_bar(stat="bin")
## when bar composition comes from different dataframe columns
gp <- ggplot(dfnum)
bar.width <- 0.5
gp <- gp + geom_bar(aes(x=factor("dairy"),
fill=factor(org.shopper.dairy)), width=bar.width)
gp <- gp + geom_bar(aes(x=factor("produce"),
fill=factor(org.shopper.produce)), width=bar.width)
## adjust legends: http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/
gp <- gp + labs(x="type of food")
gp <- gp + scale_fill_discrete(name="product\n choice",
breaks=c("0","0.5","1"),
labels=c("conv","org.domestic","org.import"))
print(gp)
## when composition is from the same column,
## but another column separates bars
p <- ggplot(data=df, aes(x=factor(1), y=Summary, fill = factor(response)))
p <- p + geom_bar(width=1) + facet_grid(facets=. ~ gender)
p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment