-2

I have the following dataset

prg<-c('BRK1','BRK2','MAN1','QN')
comp<-c(5,0,12,9)
reg<-c(0,5,0,0)
term<-c(3,0,0,0)
df<-data.frame(prg,comp,reg,term)
df

  prg comp reg term
1 BRK1    5   0    3
2 BRK2    0   5    0
3 MAN1   12   0    0
4   QN    9   0    0

Basically, I want to draw a barplot using ggplplot where prg is on the x axis and there are three bars for each of the prg in the form of comp reg and term representing the corresponding counts.

How can I go about doing this?

Nathan123
  • 763
  • 5
  • 18

3 Answers3

0

You have to melt it before plotting

1. MELTING

library(tidyverse)
df.melted <- df %>% melt(id.var="prg")
#      prg variable value
#  1  BRK1     comp     5
#  2  BRK2     comp     0
#  3  MAN1     comp    12
#  4    QN     comp     9
#  5  BRK1      reg     0
#  6  BRK2      reg     5
#  7  MAN1      reg     0
#  8    QN      reg     0
#  9  BRK1     term     3
#  10 BRK2     term     0
#  11 MAN1     term     0
#  12   QN     term     0

2. PLOTTING

## Then plot it.  
## Use the `fill` parameter to get the breakdown
library(ggplot2)
ggplot(df.melted, aes(x = prg, fil=variable, y=value)) + 
  geom_bar(stat = "identity") + 
  ggtitle("StackOverflow Roolz!")

enter image description here

Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
0

I agree with Ricardo Saporta, but I might add that without position = "dodge" the whole thing is difficult to understand.

library(tidyverse)

df.tidy <- gather(df, key, value, - prg)

ggplot(data = df.tidy, aes(x = factor(prg), y = value, col = key)) +
geom_bar(stat = "identity", position = "dodge")

this allows the bars to be spaced and distinguishable from each other.

Megazord
  • 51
  • 5
0

Using reshape2 and ggplot2:

df %>%
  melt(id.vars = "prg") %>%
  ggplot(aes(prg, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat = "identity")

enter image description here

tmfmnk
  • 38,881
  • 4
  • 47
  • 67