-2

My R is a little rusty and I'd like to figure out how to make a grouped histogram. I'd like to do a grouped histogram, which had the ratio.dis and ratio.opt grouped by "name". The data is below:

            name total ratio.dis  n ratio.opt
1 bass karen    13  2.000000  5  2.600000
2     braley    48  2.562500 16  3.000000
3        chu    18  2.166667  6  3.000000
4  cicilline    18  2.500000  6  3.000000
5    clinton    56  2.000000 18  3.111111
6    conyers    54  2.555556 18  3.000000

All the other tutorials on grouped variables used ggplot and grouped variables by "fill", but that doesn't work here, since each the categorical variable only has one value. In the histogram i hope to create, the "name" is the X value, and the two ratio variables share the same y-axis. How do I do this?

tom
  • 977
  • 3
  • 14
  • 30

2 Answers2

1

Following may be helpful:

ddf = structure(list(name = c("bass.karen", "braley", "chu", "cicilline", 
"clinton", "conyers"), total = c(13L, 48L, 18L, 18L, 56L, 54L
), ratio.dis = c(2, 2.5625, 2.166667, 2.5, 2, 2.555556), n = c(5L, 
16L, 6L, 6L, 18L, 18L), ratio.opt = c(2.6, 3, 3, 3, 3.111111, 
3)), .Names = c("name", "total", "ratio.dis", "n", "ratio.opt"
), class = "data.frame", row.names = c(NA, -6L))

ddf2 = melt(ddf[,c(1,3,5)], id='name')

ggplot(ddf2, aes(x=name, y=value, fill=variable))+geom_bar(stat='identity', position='dodge')

enter image description here

rnso
  • 23,686
  • 25
  • 112
  • 234
0

A (very simple) base R solution:

dd <- structure(list(name = c("bass.karen", "braley", "chu", "cicilline", 
"clinton", "conyers"), total = c(13L, 48L, 18L, 18L, 56L, 54L
), ratio.dis = c(2, 2.5625, 2.166667, 2.5, 2, 2.555556), n = c(5L, 
16L, 6L, 6L, 18L, 18L), ratio.opt = c(2.6, 3, 3, 3, 3.111111, 
3)), .Names = c("name", "total", "ratio.dis", "n", "ratio.opt"
), class = "data.frame", row.names = c(NA, -6L))

ddd <- cbind(dd$ratio.dis, dd$ratio.opt)
rownames(ddd) <- dd$name

barplot(t(ddd), beside = TRUE)

Note that barplot returns the position of the center of each bar, so that you can do stuff like

bp <- barplot(t(ddd), beside = TRUE)
text(bp, as.vector(t(ddd)) + 0.2, c("dis", "opt"), xpd = T)
shadowtalker
  • 12,529
  • 3
  • 53
  • 96