-1

I am learning ggplot2 and I want to plot a bar chart using the dataframe as is without converting it if possible.

Dataframe:

enter image description here

I want to plot it like this:

enter image description here

thanks,

gmarais
  • 1,801
  • 4
  • 16
  • 32
  • look at `?geom_col` and the examples. – hplieninger Jan 26 '18 at 08:54
  • 1
    Please don't share data as pictures, we can't copy those into our session. What have you tried so far? – Axeman Jan 26 '18 at 09:22
  • @Axeman sorry I tried sharing it as a table but it wasn't really "copyable" so wouldn't have helped much... how should I share the data in future? thanks – gmarais Jan 26 '18 at 09:37
  • @gmarais, there is a lot of useful advice here: [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269) Thanks! – Axeman Jan 26 '18 at 10:00
  • @gmarais: You can transform your dataframe (and other objects) into code using dput() – tjebo Jan 26 '18 at 15:43

1 Answers1

6

I made some artificial data similar to yous. I updated to include the labels:

df=data.frame(cd=seq(0,4),October=c(128,68,29,21,75),November=c(90,80,15,11,80),December=c(55,151,28,7,79))%>%
  melt(id.vars="cd",variable.name="Month")
df$cd<-as.factor(as.character(df$cd))
ggplot(df,aes(x=Month,y=value,fill=cd,label=value))+geom_col(position=position_dodge())+
  geom_text(size = 4, position =position_dodge(1),vjust=-.5)

enter image description here

Off course you could change the grouping of your data, if for instance you would like x to represent cd and colors representing Month

ggplot(df,aes(x=cd,y=value,fill=Month,label=value))+geom_col(position=position_dodge())+
  geom_text(size = 4, position =position_dodge(1),vjust=-.5)

enter image description here

Antonios
  • 1,919
  • 1
  • 11
  • 18
  • Thanks. So I have to `melt` my data in order to use ggplot as is? If you can perhaps start with that as a comment then I can accept the answer.. – gmarais Jan 26 '18 at 09:38
  • Hi gmarais, ggplot works a bit different than basic plotting in R (and excel). When you want to plot different variables (columns), instead of picking them one by one, you have to put your values in one column and use factors to goup them in other column(s). I find melt function does this work handy, but other methods might do the trick as well. – Antonios Jan 26 '18 at 09:46
  • For an overview of ways to do this transformation, see [this question](https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format). – Axeman Jan 26 '18 at 10:02