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

4
  • Ggplot2 works the best with date in the 'long' format, your table is in wide. Can you provide a dput from main? Commented Sep 22, 2018 at 10:46
  • @Wimpel Dear could you please elaborate what do you need I am new to R. Thanks Commented Sep 22, 2018 at 10:49
  • 1
    read: stackoverflow.com/questions/5963269/… Commented Sep 22, 2018 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. Commented Sep 22, 2018 at 11:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I found this is also working Thanks p <-ggplot(main, aes(main$District)) p +geom_bar(aes(fill = Sex1))
Yes, that's the more straightforward approach :) you can drop the "main$" inside the aes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.