0

I'm new to R programming as well as on Stackoverflow. I am trying to create a group bar chart (position = dodge) for two variables on y-axis and Region names on x-axis. Here is the data:

  TeenTotal SrTotal        Region
1      1882     703 North Eastern
2      2277    1028 North Central
3      1647     627      Southern
4      2299     727       Western

datatableimage

The below code is working, but for only one column (here, SrTotal):

ggplot(Chart2, aes(Region, SrTotal)) + 
 geom_bar(stat="identity", position = "dodge") + 
 scale_fill_brewer(palette = "Set1")

To get both columns, SrTotal & TeenTotal, I am trying this:

ggplot(Chart2, aes(Region, SrTotal)) + 
 ggplot(Chart2, aes(Region, TeenTotal)) +
 geom_bar(stat="identity", position = "dodge") + 
 scale_fill_brewer(palette = "Set1")

How can I show SrTotal and TeenTotal on y-axis groupbars and Region on x-axis? Also, I would like to add data labels. How can this be done?

Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • 1
    Welcome to SO. When you ask a question, could you also hand in a sample data? Nobody cannot replicate your case without it, unfortunately. – jazzurro Jan 05 '20 at 03:04
  • 1
    As other comment states, posting sample data helps. You're close, but pasting a string is difficult to use. Try reading this to easily post data: https://stackoverflow.com/questions/49994249/example-of-using-dput. – mrhellmann Jan 05 '20 at 03:18
  • 1
    My apologies for not being able to post sample data. Thank you @mrhellmann for the link. Will try to follow this next time I share any data in the question. – Pranav Dubey Jan 05 '20 at 23:06

1 Answers1

1

Some reshaping with tidyr::pivot_longer often helps for ggplot when you want to report more than one column of data.

library(tidyr); library(ggplot2)
Chart2 %>%  
  pivot_longer(TeenTotal:SrTotal, names_to = "Age", values_to = "Total") %>%
  ggplot(aes(Region, Total, fill = Age, label = Total)) +
  geom_col(position = "dodge") +
  geom_text(position = position_dodge(width = 1), vjust = 1.5)

enter image description here

Data

Chart2 <- data.frame(stringsAsFactors=FALSE,
   TeenTotal = c(1882, 2277, 1647, 2299),
     SrTotal = c(703, 1028, 627, 727),
      Region = c("North Eastern", "North Central", "Southern", "Western")
)
Jon Spring
  • 55,165
  • 4
  • 35
  • 53