5

I've got this data:

table(main$Sex1,main$District)

        Bahawalnagar Barkhan Chiniot  Faisalabad Ghotki 
Female    37           16       26       97         46          
Male      25           19       15       20         25 

I can plot it with base R

barplot(table(main$Sex1,main$District))

So my question is, how can I do this with ggplot2? Thanks

Ali Zohaib
  • 109
  • 1
  • 9
  • Ggplot2 works the best with date in the 'long' format, your table is in `wide`. Can you provide a `dput` from `main`? – Wimpel Sep 22 '18 at 10:46
  • @Wimpel Dear could you please elaborate what do you need I am new to R. Thanks – Ali Zohaib Sep 22 '18 at 10:49
  • 1
    read: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Wimpel Sep 22 '18 at 10:50
  • 2
    @wimpel `table` class is already long, it just prints in a special way. If you pass it with `as.data.frame` it will be long. – iod Sep 22 '18 at 11:05

1 Answers1

4
ggplot(as.data.frame(table(main$Sex1,main$District)), aes(Var1, Freq, fill=Var2)) + 
  geom_bar(stat="identity")

table class is long, but it prints in a special way, and ggplot doesn't know how to handle it. If you pass it with as.data.frame it will be perfectly manageable by ggplot.

iod
  • 7,412
  • 2
  • 17
  • 36
  • I found this is also working Thanks p <-ggplot(main, aes(main$District)) p +geom_bar(aes(fill = Sex1)) – Ali Zohaib Sep 22 '18 at 11:18
  • 1
    Yes, that's the more straightforward approach :) you can drop the "main$" inside the `aes`. – iod Sep 22 '18 at 11:35