[R] stacked and dodged bar graph ggplot

Robert Lynch robert.b.lynch at gmail.com
Fri Dec 30 19:30:08 CET 2016


I have some census data with race and ethnicity for various towns.  I am
trying to make a stacked bar graph where all the race data is in one
stacked bar, and all the ethnicity data is in another.

Below is a minimal reproducible sample.

library("ggplot2")

Demog <-
data.frame(source=c(rep("Davis",4),rep("Dixon",4),rep("Winters",4)),
            group =c("Asian / Pacific Islander","Caucasian","Lantinx","Not
Latinx","African American", "Native American", "Latinx", "Not
Latinx","Mixed race","Other","Latinx", "Not Latinx"),
            number =c(14491, 42571, 8172, 57450, 562, 184, 7426, 10952,
332, 1488, 3469, 3155),
            field = rep(c(rep("race",2),rep("ethnicity",2)),3))

Demog$race <- factor(Demog$group, levels=c("Asian / Pacific Islander",
"Caucasian", "African American", "Native American / Alaska Native",  "mixed
race",  "other"))
Demog$ethn <- factor(Demog$group, levels=c("Latinx","not latinx"))
Demog$location <- factor(Demog$source, levels=c( "Dixon",
"Winters","Davis"))
Demog.bar1 <-ggplot(data = Demog, aes(x = location, y = number, fill =
race))+theme_bw() +geom_bar(stat = "identity",position = "stack") +
coord_flip()

Demog.bar2 <-ggplot(data = Demog, aes(x = location, y = number, fill =
ethn))+theme_bw() +geom_bar(stat = "identity",position = "stack") +
coord_flip()

show(Demog.bar1)
show(Demog.bar2)




Much thanks,
Robert

	[[alternative HTML version deleted]]



More information about the R-help mailing list