2

I have a data frame as follows:

 reason_code num_stayed num_disconnected
       1         60                2
       2        113                3
       3        212                2
       4        451                6
.....

I basically want to plot the bar plot to compare for each reason_code, how many stayed and how many left? And I want to show these side by side. That is in the same plot. Have two bars for each reason code. One bar in (says) red the other in green.

How do I plot them in R?

MLavoie
  • 9,671
  • 41
  • 36
  • 56
frazman
  • 32,081
  • 75
  • 184
  • 269

2 Answers2

5

You can use the beside argument in barplot to accomplish this. Here's a very quick example:

example <- data.frame(reason_code=c(1,2,3,4),
                      num_stayed=c(60,113,212,451),
                      num_dx=c(2,3,2,6))

barplot(height=t(as.matrix(example[c("num_stayed","num_dx")])),beside=TRUE)

Note that I had to transpose it to get the barplot to interpret it correctly. See also this answer from Cross-Validated.

Community
  • 1
  • 1
TARehman
  • 6,659
  • 3
  • 33
  • 60
1

Here's a solution using ggplot:

require(ggplot2)
data = data.frame(reason_code = c(1,2,3,4),
                  num_stayed = c(60,113,212,451),
                  num_disconnected = c(2,3,2,6))

data = rbind(data.frame(type = "num_stayed", val = data$num_stayed, reason_code = data$reason_code), 
             data.frame(type = "num_disconnected", val = data$num_disconnected, reason_code = data$reason_code))


ggplot(data, aes(y=val, x=reason_code, fill=type)) + geom_bar(stat="identity", position="dodge")

ggplot

qwwqwwq
  • 6,999
  • 2
  • 26
  • 49
  • Please, use `reshape2` to accomplish 2d step: `data = melt(data, id.vars='reason_code')` or if you like keeping column names: `melt(data, id.vars='reason_code', variable.name = 'type', value.name='val')` – topchef Dec 07 '13 at 02:33